Java Unit 5 Notes
Java Unit 5 Notes
Unit -5
Spring Framework
Prior to the advent of Enterprise Java Beans (EJB), Java developers needed to use JavaBeans to create Web
applications. Although JavaBeans helped in the development of user interface (UI) components, they were
not able to provide services, such as transaction management and security, which were required for developing
robust and secure enterprise applications. The advent of EJB was seen as a solution to this problem EJB
extends the Java components, such as Web and enterprise components, and provides services that help in
enterprise application development.
However, developing an enterprise application with EJB was not easy, as the developer needed to perform
various tasks, such as creating Home and Remote interfaces and implementing lifecycle callback methods
which lead to the complexity of providing code for EJBs Due to this complication, developers started looking
for an easier way to develop enterprise applications.
The Spring framework(which is commonly known as Spring) has emerged as a solution to all these
complications This framework uses various new techniques such as Aspect-Oriented Programming (AOP),
Plain Old Java Object (POJO), and dependency injection (DI), to develop enterprise applications, thereby
removing the complexities involved while developing enterprise applications using EJB, Spring is an open
source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable
enterprise applications.
This framework mainly focuses on providing various ways to help us to manage our business objects.
It made the development of Web applications much easier as compared to classic Java frameworks and
Application Programming Interfaces (APIs), such as Java database connectivity(JDBC), JavaServer
Pages(JSP), and Java Servlet.
The Spring framework can be considered as a collection of sub-frameworks, also called layers, such as Spring
AOP. Spring Object-Relational Mapping (Spring ORM). Spring Web Flow, and Spring Web MVC. It is a
lightweight application framework used for developing enterprise applications
1
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
Modularity: Encourages modularity and allows for easy integration of different components.
Testability: Promotes good design and makes your application easier to test.
Ease of Use: Simplifies development with powerful tools and abstractions.
Scalability: Supports scalable and robust applications suitable for enterprise-level solutions.
The Spring Framework's extensive ecosystem and active community support make it one of the most popular
choices for building robust, maintainable, and scalable Java applications.
2
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
1. Spring Core
2. Spring AOP
3. Spring Web MVC
4. Spring DAO
5. Spring ORM
6. Spring context
7. Spring Web flow.
These modules provide different platforms to develop different enterprise applications; for example, we can
use Spring Web MVC module for developing MVC-based applications.
3
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
Dependency Injection (DI) is a design pattern that removes the dependency from the programming
code so that it can be easy to manage and test the application. Dependency Injection makes
our programming code loosely coupled.
Dependency Injection
The Dependency Injection is a design pattern that removes the dependency of the programs. In
such case we provide the information from the external source such as XML file. It makes our code loosely
coupled and easier for testing.
class Employee
Address address;
Employee(Address address)
this.address=address;
this.address=address;
In such case, instance of Address class is provided by external source such as XML file either by constructor
or setter method.
o By Constructor
o By Setter method
We can inject the dependency by constructor. The <constructor-arg> subelement of <bean> is used for
constructor injection. Here we are going to inject
To inject primitive and string-based values. We have created three files here:
o Employee.java
o applicationContext.xml
o Test.java
Employee.java
It is a simple class containing two fields id and name. There are four constructors and one method in this class.
public Employee()
{
System.out.println("def cons");
}
void show()
{
System.out.println(id+" "+name);
}
applicationContext.xml
We are providing the information into the bean by this file. The constructor-arg element invokes the
constructor. In such case, parameterized constructor of int type will be invoked. The value attribute of
constructor-arg element will assign the specified value. The type attribute specifies that int parameter
constructor will be invoked.
<beans
</bean>
</beans>
6
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
Test.java
This class gets the bean from the applicationContext.xml file and calls the show method.
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;
Employee s=(Employee)factory.getBean("e");
s.show();
7
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
If we don't specify the type attribute in the constructor-arg element, by default string type constructor will be
invoked.
....
<constructor-arg value="10"></constructor-arg>
</bean>
....
If we change the bean element as given above, string parameter constructor will be invoked and the output
will be 0 10.
Output:0 10
....
<constructor-arg value="aktu"></constructor-arg>
</bean>
....
Output:10 aktu
Address.java
This class contains three properties, one constructor and toString() method to return the values of these object.
8
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
super();
this.city = city;
this.state = state;
this.country = country;
Employee.java
It contains three properties id, name and address(dependent object) ,two constructors and show() method to
show the records of the current object including the depedent object.
void show(){
System.out.println(id+" "+name);
System.out.println(address.toString());
}
pplicationContext.xml
The ref attribute is used to define the reference of another object, such way we are passing the dependent
object as an constructor argument.
</beans>
Test.java
This class gets the bean from the applicationContext.xml file and calls the show method.
10
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;
Employee s=(Employee)factory.getBean("e");
s.show();
Spring Inversion of Control (IoC) is a fundamental concept in the Spring Framework. It refers to the design
principle where the control flow of a program is inverted compared to traditional programming. Instead of the
application code controlling the flow of execution and object creation, the framework (Spring in this case)
takes on this responsibility. This allows for more modular, decoupled, and easier-to-test code.
11
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
Spring IoC (Inversion of Control) Container is the core of Spring Framework. It creates the objects, configures
and assembles their dependencies, manages their entire life cycle.
The Container uses Dependency Injection(DI) to manage the components that make up the application.
It gets the information about the objects from a configuration file(XML) or Java Code or Java Annotations
and Java POJO class. These objects are called Beans. Since the Controlling of Java objects and their lifecycle
is not done by the developers, hence the name Inversion Of Control.
Implementation: Suppose we have one interface named Sim and it has some abstract methods calling() and
data().
Now we have created another two classes Airtel and Jio which implement the Sim interface and override the
interface methods.
// Class
// Implementing Sim interface
public class Airtel implements Sim {
// Class
// Implementing Sim interface
public class Jio implements Sim{
12
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
@Override
public void calling() {
System.out.println("Jio Calling");
}
@Override
public void data() {
System.out.println("Jio Data");
}
}
Now call these methods inside the main method. So by implementing the Run time polymorphism.
// Class
public class Mobile {
sim.calling();
sim.data();
}
}
But if in the future another new Sim Vodafone came and we need to change again to the child class name in
the code, like this-
So we have to do our configuration in the source code. We don’t want to touch the source code of this. The
source code should be constant. Here Spring IoC comes into the picture.
13
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
First, we have to create an XML file and name the file as “beans.xml“.
</beans>
In the beans.xml file, we have created beans. So inside the id, we have to pass the unique id and inside the
class, we have to pass the Class name for which you want to create the bean.
Bean Definition: In Spring, the objects that form the backbone of our application and that are managed by
the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise
managed by a Spring IoC container.
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
And now if we want to use the Airtel sim so you have to change only inside the beans.xml file. The main
method is going to be the same.
14
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
It can be defined as the breaking of code into different modules, also known as modularisation, where the
aspect is the key unit of modularity.
Aspects enable the implementation of crosscutting concerns such as- transaction, logging not central to
business logic without cluttering the code core to its functionality.
It does so by adding additional behaviour that is the advice to the existing code.
For example- Security is a crosscutting concern, in many methods in an application security rules can be
applied, therefore repeating the code at every method, define the functionality in a common class and control
were to apply that functionality in the whole application.
AOP includes programming methods and frameworks on which modularisation of code is supported and
implemented. Let’s have a look at the three dominant frameworks in AOP:
15
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
AspectJ: It is an extension for Java programming created at PARC research centre. It uses Java like
syntax and included IDE integrations for displaying crosscutting structure. It has its own compiler and
weaver, on using it enables the use of full AspectJ language.
JBoss: It is an open source Java application server developed by JBoss, used for Java development.
Spring: It uses XML based configuration for implementing AOP, also it uses annotations which are
interpreted by using a library supplied by AspectJ for parsing and matching.
Key Terminology
Aspect: An aspect is a module that encapsulates a cross-cutting concern. It contains advice and pointcuts.
Advice: Advice is the code that runs when a particular pointcut is matched. There are different types of advice,
including “before,” “after,” “around,” and “after-throwing.”
Pointcut: A pointcut is an expression that defines where an aspect’s advice should be applied in the codebase.
It selects specific join points in your application.
Join Point: A join point is a specific point in the execution of a program, such as a method call, constructor
invocation, or field access
16
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
Target Object: They are the object on which advices are applied. Spring AOP is implemented using runtime
proxies so this object is always a proxied object. What is means is that a subclass is created at runtime where
the target method is overridden and advice are included based on their configuration.
AOP proxy: Spring AOP implementation uses JDK dynamic proxy to create the Proxy classes with target
classes and advice invocations, these are called AOP proxy classes. We can also use CGLIB proxy by adding
it as the dependency in the Spring AOP project.
Weaving: It is the process of linking aspects with other objects to create the advised proxy objects. This can
be done at compile time, load time or at runtime. Spring AOP performs weaving at the runtime
Bean Scopes refers to the lifecycle of Bean that means when the object of Bean will be instantiated, how long
does that object live, and how many objects will be created for that bean throughout. Basically, it controls the
instance creation of the bean and it is managed by the spring container.
The spring framework provides five scopes for a bean. We can use three of them only in the context of web-
aware Spring ApplicationContext and the rest of the two is available for both IoC container and Spring-
MVC container.
1. Singleton: Only one instance will be created for a single bean definition per Spring IoC container and
the same object will be shared for each request made for that bean.
2. Prototype: A new instance will be created for a single bean definition every time a request is made
for that bean.
3. Request: A new instance will be created for a single bean definition every time an HTTP request is
made for that bean. But Only valid in the context of a web-aware Spring ApplicationContext.
4. Session: Scopes a single bean definition to the lifecycle of an HTTP Session. But Only valid in the
context of a web-aware Spring ApplicationContext.
5. Global-Session: Scopes a single bean definition to the lifecycle of a global HTTP Session. It is also
only valid in the context of a web-aware Spring ApplicationContext.
17
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
Singleton Scope:
If the scope is a singleton, then only one instance of that bean will be instantiated per Spring IoC container
and the same instance will be shared for each request.
That is when the scope of a bean is declared singleton, then whenever a new request is made for that bean,
spring IOC container first checks whether an instance of that bean is already created or not. If it is already
created, then the IOC container returns the same instance otherwise it creates a new instance of that bean only
at the first request. By default, the scope of a bean is a singleton.
Step1: First create a bean (i.e.), the backbone of the application in the spring framework.
Step 2: Now, we write a Spring XML configuration file “spring.xml” and configure the bean defined
above.
< bean
id = "hw"
class= "bean.HelloWorld"
scope = "singleton" / >
</beans>
Step 3: Finally, write a driver class “Client.java” to request the above bean.
package driver;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import bean.HelloWorld;
Explanation:
When we call the getName() method by using the reference of ‘Geeks1’ and ‘Geeks2’, then we are getting the
same outputs. This means that both the reference is calling the getName() method of the same object.
Furthermore, when we are comparing the reference ‘Geeks1’ and ‘Geeks2’ then output is “true” which means
the same object is shared between ‘Geeks1’ and ‘Geeks2’. So it is clear that a new instance of bean
(HelloWorld) is created when we made the request the first time and for each new request, the same object is
being shared.
Prototype Scope:
If the scope is declared prototype, then spring IOC container will create a new instance of that bean every
time a request is made for that specific bean. A request can be made to the bean instance either
programmatically using getBean() method or by XML for Dependency Injection of secondary type.
Generally, we use the prototype scope for all beans that are stateful, while the singleton scope is used for the
stateless beans.
Prototype Scope:
If the scope is declared prototype, then spring IOC container will create a new instance of that bean every
time a request is made for that specific bean. A request can be made to the bean instance either
programmatically using getBean() method or by XML for Dependency Injection of secondary type.
Generally, we use the prototype scope for all beans that are stateful, while the singleton scope is used for the
stateless beans.
Step 1: First create a bean (i.e.), the backbone of the application in the spring framework.
20
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
Step 2: Now, we write a Spring XML configuration file “spring.xml” and configure the bean defined above.
Step 3: Finally, write a driver class “Client.java” to request the above bean.
// Java program to illustrate
// the client to perform the
// request to the defined bean
package driver;
import org.springframework
.context.ApplicationContext;
import org.springframework.context.support
.ClassPathXmlApplicationContext;
import bean.HelloWorld;
21
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
Explanation:
When we call getName() method by using the reference ‘Geeks1’ and ‘Geeks2’, then we get different outputs
that means both the reference is calling getName() method of a different object. Furthermore, when we are
comparing the reference ‘Geeks1’ and ‘Geeks2’ then output is “false” which means both references is referring
to a different object. So it is clear that a new instance of bean (HelloWorld) is being created at each request
made for this bean.
22
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
Singleton Prototype
Only one instance is created for a single bean definition A new instance is created for a single bean
per Spring IoC container definition every time a request is made for that
bean.
Same object is shared for each request made for that For each new request a new instance is created.
bean. i.e. The same object is returned each time it is i.e. A new object is created each time it is
injected. injected.
By default scope of a bean is singleton. So we don’t By default scope is not prototype so you have to
need to declare a been as singleton explicitly. declare the scope of a been as prototype
explicitly.
Singleton scope should be used for stateless beans. While prototype scope is used for all beans that
are stateful
Request Scope:
In request scope, container creates a new instance for each and every HTTP request. So, if the server is
currently handling 50 requests, then the container can have at most 50 individual instances of the bean class.
Any state change to one instance, will not be visible to other instances. A bean instance is destructed as soon
as the request is completed.
Java Configuration:
@Bean
@Scope(value =
WebApplicationContext.SCOPE_REQUEST,
proxyMode = ScopedProxyMode.TARGET_CLASS)
public class BeanClass
{
System.out.println("A new BeanClass instance created for current request");
return new BeanClass();
}
//or
@Component
@RequestScope
public class BeanClass
{
}
23
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
XML Configuration:
<bean id="beanId" class="com.howtodoinjava.BeanClass" scope="request" />
We need a proxyMode attribute because when web-aware context is instantiated, we don’t have any HTTP
request. Therefore, Spring injects the proxy as a dependency and instantiate the bean when HTTP request is
invoked. OR, in short we can annotate with @RequestScope, a shortcut for above.
The same is applicable for the other web-aware scopes i.e. session scope, application scope, and websocket
scope.
Session Scope
In session scope, the application context creates a new instance for each and every HTTP session. So, if the
server has 20 active sessions, then the container can have at most 20 individual instances of the bean class.
All HTTP requests within a single session lifetime will have access to the same single bean instance in that
session scope.
Any state change to one instance will not be visible to other instances. An instance is destructed as soon as
the session ends. The @SessionScope annotation works as a shortcut for @Scope(“session”) declaration.
Java Configuration:
@Bean
@Scope(value =
WebApplicationContext.SCOPE_SESSION,
proxyMode = ScopedProxyMode.TARGET_CLASS)
public class BeanClass {
System.out.println("A new BeanClass instance created for current request");
return new BeanClass();
}
//or
@Component
@SessionScope
public class BeanClass {
}
XML Configuration:
<bean id="beanId" class="com.howtodoinjava.BeanClass" scope="session" />
24
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
Application Scope
In application scope, the container creates one instance per web application runtime. It is almost similar
to singleton scope with only two differences i.e.
1. The application scoped bean is singleton per ServletContext, whereas singleton scoped bean is
singleton per ApplicationContext. Please note that there can be multiple application contexts within a
single application.
2. The application scoped bean is visible as a ServletContext attribute.
Java Configuration:
@Bean
@Scope(value =
WebApplicationContext.SCOPE_APPLICATION,
proxyMode = ScopedProxyMode.TARGET_CLASS)
public class BeanClass {
System.out.println("A new BeanClass instance created for current request");
return new BeanClass();
}
//or
@Component
@ApplicationScope
public class BeanClass {
}
XML Configuration:
<bean id="beanId" class="com.howtodoinjava.BeanClass" scope="application" />
WebSocket Scope:
The WebSocket Protocol enables two-way communication between a client and a remote host that has opted-
in to communicate with the client. WebSocket Protocol provides a single TCP connection for traffic in both
directions. This is especially useful for multi-user applications with simultaneous editing and multi-user
games.
In this type of web application, HTTP is used only for the initial handshake. The server can respond with
HTTP status 101 (switching protocols) if it agrees – to the handshake request. If the handshake succeeds, the
TCP socket remains open, and both the client and server can use it to send messages to each other.
25
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
When first accessed, WebSocket scoped beans are stored in the WebSocket session attributes. The same bean
instance is then returned during the entire WebSocket session.
Please note that websocket scoped beans are typically singleton and live longer than any individual
WebSocket session.
Java Configuration:
@Component
@Scope(scopeName = "websocket",
proxyMode = ScopedProxyMode.TARGET_CLASS)
public class BeanClass {
}
XML Configuration:
<bean id="beanId" class="com.howtodoinjava.BeanClass" scope="websocket" />
Spring – Autowiring
Autowiring in the Spring framework can inject dependencies automatically. The Spring container detects
those dependencies specified in the configuration file and the relationship between the beans. This is referred
to as Autowiring in Spring. To enable Autowiring in the Spring application we should
use @Autowired annotation. Autowiring in Spring internally uses constructor injection. An autowired
application requires fewer lines of code comparatively but at the same time, it provides very little flexibility
to the programmer.
Modes of Autowiring
Modes Description
No This mode tells the framework that autowiring is not
supposed to be done. It is the default mode used by
Spring.
byName It uses the name of the bean for injecting
dependencies.
byType It injects the dependency according to the type of
bean.
Constructor It injects the required dependencies by invoking the
constructor.
26
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
1. No
This mode tells the framework that autowiring is not supposed to be done. It is the default mode used by
Spring.
2. byName
It uses the name of the bean for injecting dependencies. However, it requires that the name of the property and
bean must be the same. It invokes the setter method internally for autowiring.
3. byType
It injects the dependency according to the type of the bean. It looks up in the configuration file for the class
type of the property. If it finds a bean that matches, it injects the property. If not, the program throws an error.
The names of the property and bean can be different in this case. It invokes the setter method internally for
autowiring.
4. constructor
It injects the required dependencies by invoking the constructor. It works similar to the “byType” mode but it
looks for the class type of the constructor arguments. If none or more than one bean are detected, then it throws
an error, otherwise, it autowires the “byType” on all constructor arguments.
27
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
</bean>
<bean id="city" class="sample.City" autowire="constructor"></bean>
5. autodetect
The autodetect mode uses two other modes for autowiring – constructor and byType. It first tries to autowire
via the constructor mode and if it fails, it uses the byType mode for autowiring. It works in Spring 2.0 and 2.5
but is deprecated from Spring 3.0 onwards.
Example of Autowiring
State.java
City.java
class City {
private int id;
private String name;
private State s;
public int getID() { return id; }
public void setId(int eid) { this.id = eid; }
public String getName() { return name; }
public void setName(String st) { this.name = st; }
public State getState() { return s; }
@Autowired public void setState(State sta)
{
this.s = sta;
}
public void showCityDetails()
{
System.out.println("City Id : " + id);
System.out.println("City Name : " + name);
System.out.println("State : " + s.getName());
}
28
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args)
{
SpringApplication.run(DemoApplication.class, args);
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
City cty = context.getBean("city", City.class);
cty.setId(01);
cty.setName("Varanasi");
State st = context.getBean("state", State.class);
st.setName("UP");
cty.setState(st);
cty.showCityDetails();
}
}
Note:
Advantage of Autowiring: It requires less code because we don’t need to write the code to inject the
dependency explicitly.
Disadvantage of Autowiring: No control of the programmer and It can’t be used for primitive and string
values.
29
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
Spring Annotations
@Service
Annotate all your service classes with @Service. All your business logic should be in Service classes.
@Service
...
@Repository
Annotate all your DAO classes with @Repository. All your database access logic should be in DAO classes.
@Repository
...
30
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
@Component
Annotate your other components (for example REST resource classes) with @Component.
@Component
...
@Component is a generic stereotype for any Spring-managed component. @Repository, @Service, and
@Controller are specializations of @Component for more specific use cases, for example, in the persistence,
service, and presentation layers, respectively.
@Autowired
Let Spring auto-wire other beans into your classes using @Autowired annotation.
@Service
@Autowired
31
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
...
@Transactional
@Service
@Autowired
@Transactional
return company;
..
@Scope
As with Spring-managed components in general, the default and most common scope for autodetected
components is singleton. To change this default behavior, use @Scope spring annotation.
@Component
@Scope("request")
...
32
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
Similarly, you can annotate your component with @Scope("prototype") for beans with prototype scopes.
Bean lifecycle simply means we want to execute callbacks before the spring bean is available to use and
similarly execute callbacks before the bean is destroyed.
There are several ways to configure the Spring bean lifecycle callbacks as listed below.
1. The JSR-250 specification using @PostConstruct and @PreDestroy annotations. This is the
recommended way.
The below diagram shows the different stages spring bean goes through before it is ready to use.
33
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
In Spring and Spring Boot, beans represent objects that are managed by the Spring container and are
responsible for providing services, such as data access, business logic, or infrastructure functionality. In this
article, we’ll explore various ways to configure beans in Spring and Spring Boot.
There are multiple ways to configure beans in Spring and Spring Boot:
Java Configuration: Spring provides @Configuration and @Bean annotations to define beans using
Java configuration classes.
34
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
XML Configuration (Spring XML Schema): Beans can be defined in XML configuration files using
the <bean> element. While XML configuration is less common in modern Spring applications, it is
still supported for legacy and specific use cases.
Annotation-based configuration is the most common approach used in modern Spring applications. When
Spring loads, Java beans are scanned in the following places:
@Configuration
@ComponentScan(basePackages = "com.howtodoinjava.spring")
When component scanning is enabled, we can define the beans using one of the following annotations as
appropriate.
@Component
@Repository
@Service
@Controller
@RestController
package com.howtodoinjava.spring.service;
@Service
35
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
//...
//Method 1
//Method 2
ctx.register(AppConfig.class);
ctx.refresh();
Instead of annotating the classes with Spring annotations, we can declare them as Spring bean in the
configuration class:
@Configuration
@Bean
36
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
Now we can load this bean into the application context as follows:
//Method 1
//Method 2
ctx.register(AppConfig.class);
ctx.refresh();
4. XML Configuration
XML configuration involves defining beans in XML files using the <bean> element. While less common than
annotation-based and Java configuration, XML configuration is still supported in Spring.
37
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
Spring Boot
Spring Boot is a project that is built on the top of the Spring Framework. It provides an easier and faster way
to set up, configure, and run both simple and web-based applications.
It is a Spring module that provides the RAD (Rapid Application Development) feature to the Spring
Framework. It is used to create a stand-alone Spring-based application that you can just run because it needs
minimal Spring configuration.
In short, Spring Boot is the combination of Spring Framework and Embedded Servers.
In Spring Boot, there is no requirement for XML configuration (deployment descriptor). It uses convention
over configuration software design paradigm that means it decreases the effort of the developer.
We can use Spring STS IDE or Spring Initializr to develop Spring Boot Java applications.
38
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
o It simplifies integration with other Java frameworks like JPA/Hibernate ORM, Struts, etc.
o It reduces the cost and development time of the application.
Along with the Spring Boot Framework, many other Spring sister projects help to build applications
addressing modern business needs. There are the following Spring sister projects are as follows:
o Spring Data: It simplifies data access from the relational and NoSQL databases.
o Spring Batch: It provides powerful batch processing.
o Spring Security: It is a security framework that provides robust security to applications.
o Spring Social: It supports integration with social networking like LinkedIn.
o Spring Integration: It is an implementation of Enterprise Integration Patterns. It facilitates integration
with other enterprise applications using lightweight messaging and declarative adapters.
o It creates stand-alone Spring applications that can be started using Java -jar.
o It tests web applications easily with the help of different Embedded HTTP servers such as Tomcat,
Jetty, etc. We don't need to deploy WAR files.
o It provides opinionated 'starter' POMs to simplify our Maven configuration.
o It provides production-ready features such as metrics, health checks, and externalized
configuration.
o There is no requirement for XML configuration.
o It offers a CLI tool for developing and testing the Spring Boot application.
o It offers the number of plug-ins.
o It also minimizes writing multiple boilerplate codes (the code that has to be included in many places
with little or no alteration), XML configuration, and annotations.
o It increases productivity and reduces development time.
Spring Boot can use dependencies that are not going to be used in the application. These dependencies increase
the size of the application.
39
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
Annotations are a form of hints that a developer can give about their program to the compiler and runtime.
Based on these hints, the compilers and runtimes can process these programs differently. That is exactly what
happens with annotations in spring boot. Spring Boot uses relies on annotations extensively to define and
process bean definitions. Some of the features we discuss here are from Spring Framework. But Spring Boot
itself is an opinionated version of Spring.
@Bean
You should use the @Bean on a method that returns a bean object. For example, you could define a bean as
shown below.
@Bean
public MyService getMyService(){
MyDto dto = new MyDtoImpl();
MyService myService = new MyServiceImpl();
myService.setDto(dto);
return myService
}
Code language: Java (java)
@Autowired
The @Autowired annotation lets you inject a bean wherever you want(most importantly factory methods like
the one we seen above). For example, we needed a MyDto for MyService in our previous example. As we had
to hardcode in that example, you can simplify it as shown here.
@Bean
public MyDto myDto() {
return new CustomDtoImpl();
}
40
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
@Bean
public MyService myServiceUsingAutowiring(@Autowired MyDto myDto) {
MyService myService = new MyServiceImpl(myDto);
return myService;
}
Code language: Java (java)
As you see here, @Autowired annotation makes sure spring boot loads an appropriate MyDto bean. Note that,
you would get an error if you haven’t defined a MyDto bean. You could work around this by
setting @Autowired(required=false).
@Bean
public MyService myServiceUsingAutowiringRequiredFalse(@Autowired(required = false) MyDto myDto)
{
if(myDto==null){
myDto = new DefaultMyDtoImpl();
}
MyService myService = new MyServiceImpl(myDto);
return myService;
}
Code language: Java (java)
This approach provides you a default approach that you can override later.
You could also use the @Autowired annotation for arbitrary number of beans. This is done by setting the
annotation at the method level. For instance, take a look at this snippet.
@Bean
@Autowired
public OrderService myServiceUsingAutowireMultiple(PaymentService paymentService,
StockService stockService,
EmailService emailService) {
@Required
Similar to setting required flag in @Autowired, you should use this annotation to mark a certain field or setter
method as required. For instance, take a look at this snippet.
41
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
@Required
public void setMovieFinder(PaymentService paymentService) {
this.paymentService = paymentService;
}
//do stuff
}
Code language: Java (java)
@SpringBootApplication
The @SpringBootApplication annotation is often used in the main class. This annotation is equivalent to
using @Configuration, @EnableAutoConfiguration and @ComponentScan together. This annotation is
responsible for setting up which autoconfiguration to enable and where to look for spring bean components
and configurations.
@SpringBootApplication
public class SpringHowApplication {
public static void main(String[] args) {
SpringApplication.run(SpringHowApplication.class, args);
}
}
Code language: Java (java)
@Configuration
This annotation is used together with the bean definition annotations. When the @ComponentScan finds a
class that is annotated with @Configuration, it will try to process all @Bean and other spring related methods
inside it.
@Configuration
public class BeanDefinitionExamples {
@Bean
public MyService myService() {
MyDto myDto = new MyDtoImpl();
MyService myService = new MyServiceImpl(myDto);
return myService;
}
//more beans
}
42
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
Configuration properties
This spring boot specific annotation helps bind properties file entries to a java bean. For example, take a look
at these configs.
app.maxOrderPriceLimit=1000
app.payment.enabled=true
app.payment.types=card,cash
Code language: Java (java)
Let’s map these into a java bean.
@Configuration
@ConfigurationProperties("app")
public class AppConfig {
private int maxOrderPriceLimit = 0;
private PaymentConfig payment;
//getter setter
static class PaymentConfig {
List<String> types;
boolean enabled;
//getter setter
}
}
Code language: Java (java)
If setup correctly, Spring boot will create a AppConfig bean object with values mapped from properties.
Subsequently, We can autowire them wherever we want.
Spring Boot Actuator is a sub-project of the Spring Boot Framework. It includes a number of additional
features that help us to monitor and manage the Spring Boot application. It contains the actuator endpoints
(the place where the resources live). We can use HTTP and JMX endpoints to manage and monitor the Spring
Boot application. If we want to get production-ready features in an application, we should use the Spring
Boot actuator.
o Endpoints
o Metrics
o Audit
43
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
Endpoint: The actuator endpoints allows us to monitor and interact with the application. Spring Boot provides
a number of built-in endpoints. We can also create our own endpoint. We can enable and disable each endpoint
individually. Most of the application choose HTTP, where the Id of the endpoint, along with the prefix
of /actuator, is mapped to a URL.
o For example, the /health endpoint provides the basic health information of an application. The
actuator, by default, mapped it to /actuator/health.
o Metrics: Spring Boot Actuator provides dimensional metrics by integrating with the micrometer. The
micrometer is integrated into Spring Boot. It is the instrumentation library powering the delivery of
application metrics from Spring. It provides vendor-neutral interfaces for timers, gauges, counters,
distribution summaries, and long task timers with a dimensional data model.
o Audit: Spring Boot provides a flexible audit framework that publishes events to
an AuditEventRepository. It automatically publishes the authentication events if spring-security is in
execution.
We can enable actuator by injecting the dependency spring-boot-starter-actuator in the pom.xml file.
1. <dependency>
2. <groupId>org.springframework.boot</groupId>
3. <artifactId>spring-boot-starter-actuator</artifactId>
4. <version>2.2.2.RELEASE</version>
5. </dependency>
The actuator endpoints allow us to monitor and interact with our Spring Boot application. Spring Boot includes
number of built-in endpoints and we can also add custom endpoints in Spring Boot application.
Id Usage Default
actuator It provides a hypermedia-based discovery page for the other endpoints. True
It requires Spring HATEOAS to be on the classpath.
auditevents It exposes audit events information for the current application. True
44
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
beans It is used to display a complete list of all the Spring beans in your True
application.
flyway It is used to show any Flyway database migrations that have been True
applied.
loggers It is used to show and modify the configuration of loggers in the True
application.
liquibase It is used to show any Liquibase database migrations that have been True
applied.
metrics It is used to show metrics information for the current application. True
Id Description Default
heapdump It is used to return a GZip compressed hprof heap dump file. True
jolokia It is used to expose JMX beans over HTTP (when Jolokia is on the True
classpath).
45
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
Dependency Management
Spring Boot team provides a list of dependencies to support the Spring Boot version for its every release.
You do not need to provide a version for dependencies in the build configuration file. Spring Boot
automatically configures the dependencies version based on the release. Remember that when you upgrade
the Spring Boot version, dependencies also will upgrade automatically.
Note − If you want to specify the version for dependency, you can specify it in your configuration file.
However, the Spring Boot team highly recommends that it is not needed to specify the version for
dependency.
Maven Dependency
For Maven configuration, we should inherit the Spring Boot Starter parent project to manage the Spring Boot
Starters dependencies. For this, simply we can inherit the starter parent in our pom.xml file as shown below.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
</parent>
We should specify the version number for Spring Boot Parent Starter dependency. Then for other starter
dependencies, we do not need to specify the Spring Boot version number. Observe the code given below −
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
Gradle Dependency
46
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
We can import the Spring Boot Starters dependencies directly into build.gradle file. We do not need Spring
Boot start Parent dependency like Maven for Gradle. Observe the code given below −
buildscript {
ext {
springBootVersion = '1.5.8.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
Similarly, in Gradle, we need not specify the Spring Boot version number for dependencies. Spring Boot
automatically configures the dependency based on the version.
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
}
Default package
A class that does not have any package declaration is considered as a default package. Note that generally
a default package declaration is not recommended. Spring Boot will cause issues such as malfunctioning of
Auto Configuration or Component Scan, when you use default package.
Note − Java's recommended naming convention for package declaration is reversed domain name. For
example − com.tutorialspoint.myproject
Typical Layout
The typical layout of Spring Boot application is shown in the image given below −
47
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
The Application.java file should declare the main method along with @SpringBootApplication. Observe the
code given below for a better understanding −
package com.tutorialspoint.myproject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}
Application Runner
Application Runner is an interface used to execute the code after the Spring Boot application started. The
example given below shows how to implement the Application Runner interface on the main class file.
package com.tutorialspoint.demo;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication implements ApplicationRunner {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
48
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
@Override
public void run(ApplicationArguments arg0) throws Exception {
System.out.println("Hello World from Application Runner");
}
}
Command Line Runner is an interface. It is used to execute the code after the Spring Boot application started.
The example given below shows how to implement the Command Line Runner interface on the main class
file.
package com.tutorialspoint.demo;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(String... arg0) throws Exception {
System.out.println("Hello world from Command Line Runner");
}
}
Spring Boot provides a very good support to building RESTful Web Services for enterprise applications.
This chapter will explain in detail about building RESTful web services using Spring Boot.
Note − For building a RESTful Web Services, we need to add the Spring Boot Starter Web dependency into
the build configuration file.
If you are a Maven user, use the following code to add the below dependency in your pom.xml file −
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
If you are a Gradle user, use the following code to add the below dependency in your build.gradle file.
49
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
compile('org.springframework.boot:spring-boot-starter-web')
The code for complete build configuration file Maven build – pom.xml is given below −
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
50
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
The code for complete build configuration file Gradle Build – build.gradle is given below −
buildscript {
ext {
springBootVersion = '1.5.8.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
Before you proceed to build a RESTful web service, it is suggested that you have knowledge of the following
annotations −
Rest Controller
The @RestController annotation is used to define the RESTful web services. It serves JSON, XML and
custom response. Its syntax is shown below −
@RestController
public class ProductServiceController {
51
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
Request Mapping
The @RequestMapping annotation is used to define the Request URI to access the REST Endpoints. We can
define Request method to consume and produce object. The default request method is GET.
@RequestMapping(value = "/products")
public ResponseEntity<Object> getProducts() { }
Request Body
The @RequestBody annotation is used to define the request body content type.
public ResponseEntity<Object> createProduct(@RequestBody Product product) {
}
Path Variable
The @PathVariable annotation is used to define the custom or dynamic request URI. The Path variable in
request URI is defined as curly braces {} as shown below −
public ResponseEntity<Object> updateProduct(@PathVariable("id") String id) {
}
Request Parameter
The @RequestParam annotation is used to read the request parameters from the Request URL. By default, it
is a required parameter. We can also set default value for request parameters as shown here −
public ResponseEntity<Object> getProduct(
@RequestParam(value = "name", required = false, defaultValue = "honey") String name) {
}
GET API
The default HTTP request method is GET. This method does not require any Request Body. You can send
request parameters and path variables to define the custom or dynamic URL.
The sample code to define the HTTP GET request method is shown below. In this example, we used
HashMap to store the Product. Note that we used a POJO class as the product to be stored.
Here, the request URI is /products and it will return the list of products from HashMap repository. The
controller class file is given below that contains GET method REST Endpoint.
package com.tutorialspoint.demo.controller;
import java.util.HashMap;
52
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.tutorialspoint.demo.model.Product;
@RestController
public class ProductServiceController {
private static Map<String, Product> productRepo = new HashMap<>();
static {
Product honey = new Product();
honey.setId("1");
honey.setName("Honey");
productRepo.put(honey.getId(), honey);
POST API
The HTTP POST request is used to create a resource. This method contains the Request Body. We can send
request parameters and path variables to define the custom or dynamic URL.
The following example shows the sample code to define the HTTP POST request method. In this example,
we used HashMap to store the Product, where the product is a POJO class.
Here, the request URI is /products, and it will return the String after storing the product into HashMap
repository.
package com.tutorialspoint.demo.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
53
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.tutorialspoint.demo.model.Product;
@RestController
public class ProductServiceController {
private static Map<String, Product> productRepo = new HashMap<>();
PUT API
The HTTP PUT request is used to update the existing resource. This method contains a Request Body. We
can send request parameters and path variables to define the custom or dynamic URL.
The example given below shows how to define the HTTP PUT request method. In this example, we used
HashMap to update the existing Product, where the product is a POJO class.
Here the request URI is /products/{id} which will return the String after a the product into a HashMap
repository. Note that we used the Path variable {id} which defines the products ID that needs to be updated.
package com.tutorialspoint.demo.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.tutorialspoint.demo.model.Product;
@RestController
public class ProductServiceController {
private static Map<String, Product> productRepo = new HashMap<>();
54
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
DELETE API
The HTTP Delete request is used to delete the existing resource. This method does not contain any Request
Body. We can send request parameters and path variables to define the custom or dynamic URL.
The example given below shows how to define the HTTP DELETE request method. In this example, we used
HashMap to remove the existing product, which is a POJO class.
The request URI is /products/{id} and it will return the String after deleting the product from HashMap
repository. We used the Path variable {id} which defines the products ID that needs to be deleted.
package com.tutorialspoint.demo.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.tutorialspoint.demo.model.Product;
@RestController
public class ProductServiceController {
private static Map<String, Product> productRepo = new HashMap<>();
55
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
This section gives you the complete set of source code. Observe the following codes for their respective
functionalities −
The Spring Boot main application class – DemoApplication.java
package com.tutorialspoint.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
The POJO class – Product.java
package com.tutorialspoint.demo.model;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
56
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.tutorialspoint.demo.model.Product;
@RestController
public class ProductServiceController {
private static Map<String, Product> productRepo = new HashMap<>();
static {
Product honey = new Product();
honey.setId("1");
honey.setName("Honey");
productRepo.put(honey.getId(), honey);
@RequestMapping(value = "/products")
public ResponseEntity<Object> getProduct() {
57
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science
58
S
U
D