Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
28 views

Java Unit 5 Notes

Uploaded by

Arib Ahmed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Java Unit 5 Notes

Uploaded by

Arib Ahmed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

IMS Engineering College

NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.


Tel: (0120) 4940000
Department: Computer Science

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

Spring is a lightweight framework developed by Rod Johnson in 2003. It can be thought of as a


framework of frameworks because it provides support to various frameworks such as Struts,,
Hibernate, Tapestry, EJB, JSF, etc. The framework, in broader sense, can be defined as a structure
where we find solution of the various technical problems. The Spring framework comprises several
modules such as IOC, AOP, DAO, Context, ORM, WEB MVC etc.

1
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science

Benefits of Using Spring Framework:

 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.

Spring Framework Architecture

2
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science

The Spring framework consists of seven modules. These modules are :

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 in Spring

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;

public void setAddress(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.

Two ways to perform Dependency Injection in Spring framework

Spring framework provides two ways to inject dependency


IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science

o By Constructor
o By Setter method

Dependency Injection by Constructor

We can inject the dependency by constructor. The <constructor-arg> subelement of <bean> is used for
constructor injection. Here we are going to inject

1. primitive and String-based values


2. Dependent object (contained object)
3. Collection values etc.

Injecting primitive and string-based values:

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 class Employee


{

private int id;


private String name;

public Employee()
{
System.out.println("def cons");
}

public Employee(int id)


{
this.id = id;
5
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science

public Employee(String name)


{
this.name = name;
}

public Employee(int id, String name)


{
this.id = id;
this.name = name;
}

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.

<?xml version="1.0" encoding="UTF-8"?>

<beans

<bean id="e" class=" Employee">

<constructor-arg value="10" type="int"></constructor-arg>

</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.*;

public class Test

public static void main(String[] args)

Resource r=new ClassPathResource("applicationContext.xml");

BeanFactory factory=new XmlBeanFactory(r);

Employee s=(Employee)factory.getBean("e");

s.show();

Injecting string-based values:s

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.

....

<bean id="e" class="Employee">

<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

We may pass integer literal and string both as following

....

<bean id="e" class="com.javatpoint.Employee">

<constructor-arg value="10" type="int" ></constructor-arg>

<constructor-arg value="aktu"></constructor-arg>

</bean>

....

Output:10 aktu

Constructor Injection with Dependent Object:

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

public class Address

private String city;

private String state;

private String country;

public Address(String city, String state, String country)

super();

this.city = city;

this.state = state;

this.country = country;

public String toString()

return city+" "+state+" "+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.

public class Employee {


private int id;
9
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science

private String name;


private Address address;//Aggregation

public Employee() {System.out.println("def cons");}

public Employee(int id, String name, Address address) {


super();
this.id = id;
this.name = name;
this.address = address;
}

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.

<?xml version="1.0" encoding="UTF-8"?>


<beans
<bean id="a1" class="Address">
<constructor-arg value="ghaziabad"></constructor-arg>
<constructor-arg value="UP"></constructor-arg>
<constructor-arg value="India"></constructor-arg>
</bean>

<bean id="e" class="Employee">


<constructor-arg value="12" type="int"></constructor-arg>
<constructor-arg value="aktu"></constructor-arg>
<constructor-arg>
<ref bean="a1"/>
</constructor-arg>
</bean>

</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.*;

public class Test {

public static void main(String[] args) {

Resource r=new ClassPathResource("applicationContext.xml");

BeanFactory factory=new XmlBeanFactory(r);

Employee s=(Employee)factory.getBean("e");

s.show();

Spring Inversion of Control

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().

// Java Program to Illustrate Sim Interface


public interface Sim
{
void calling();
void data();
}

Now we have created another two classes Airtel and Jio which implement the Sim interface and override the
interface methods.

// Java Program to Illustrate Airtel Class

// Class
// Implementing Sim interface
public class Airtel implements Sim {

@Override public void calling()


{
System.out.println("Airtel Calling");
}

@Override public void data()


{
System.out.println("Airtel Data");
}
}

// Java Program to Illustrate Jio Class

// 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.

// Java Program to Illustrate Mobile Class

// Class
public class Mobile {

// Main driver method


public static void main(String[] args)
{

// Creating instance of Sim interface


// inside main() method
// with reference to Jio class constructor
// invocation
Sim sim = new Jio();

// Sim sim = new Airtel();

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-

Sim sim = new Vodafone();

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.

So in this example, we are going to use ApplicationContext to implement an IoC container.

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“.

Example: beans.xml File

<?xml version="1.0" encoding="UTF-8"?>


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="sim" class="Jio"></bean>

</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;

public class Mobile


{
public static void main(String[] args) {
// Using ApplicationContext tom implement Spring IoC
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");

// Get the bean


Sim sim = applicationContext.getBean("sim", Sim.class);

// Calling the methods


sim.calling();
sim.data();
}
}

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

<bean id="sim" class="Airtel"></bean>

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Mobile {


public static void main(String[] args) {

// Using ApplicationContext tom implement Spring IoC


ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");

// Get the bean


Sim sim = applicationContext.getBean("sim", Sim.class);

// Calling the methods


sim.calling();
sim.data();
}
}

Aspect Oriented Programming and AOP in Spring

Aspect oriented programming(AOP) as the name suggests uses aspects in programming.

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.

Dominant Frameworks in AOP:

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 in Java Spring

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.

Bean Scopes in Spring

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.

The following are the different scopes provided for a bean:

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.

// Java program to illustrate a bean


// created in the spring framework
package bean;

public class HelloWorld {


public String name;

// Create a setter method to


// set the value passed by user
public void setName(String name)
{
this.name = name;
}

// Create a getter method so that


// the user can get the set value
public String getName()
{
return name;
}
}

Step 2: Now, we write a Spring XML configuration file “spring.xml” and configure the bean defined
above.

<!DOCTYPE beans PUBLIC


"-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<!--configure the bean HelloWorld.java
and declare its scope-->
18
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science

< bean
id = "hw"
class= "bean.HelloWorld"
scope = "singleton" / >
</beans>

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;

// Client Class to request the


// above defined bean
public class Client {

public static void main(String[] args)


{
// Load the Spring XML configuration
// file into IoC container
ApplicationContext ap= new ClassPathXmlApplicationContext("resources/spring.xml");

// Get the "HelloWorld" bean object


// and call getName() method
HelloWorld Geeks1= (HelloWorld)ap.getBean("hw");

// Set the name


Geeks1.setName("Geeks1");
System.out.println("Hello object (hello1)"+ " Your name is: "+ Geeks1.getName());

// Get another "HelloWorld" bean object


// and call getName() method
HelloWorld Geeks2= (HelloWorld)ap.getBean("hw");

System.out.println("Hello object (hello2)"+ " Your name is: "+ Geeks2.getName());

// Now compare the references to see


// whether they are pointing to the
19
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science

// same object or different object


System.out.println("'Geeks1' and 'Geeks2'"+ " are referring"+ "to the same object: "+ (Geeks1 == Geeks2));

// Print the address of both


// object Geeks1 and Geeks2
System.out.println("Address of object Geeks1: "+ Geeks1);
System.out.println("Address of object Geeks2: "+ Geeks2);
}
}

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.

// Java program to illustrate a bean


// created in the spring framework
package bean;

public class HelloWorld {


public String name;

20
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science

// Create a setter method to


// set the value passed by user
public void setName(String name)
{
this.name = name;
}

// Create a getter method so that


// the user can get the set value
public String getName()
{
return name;
}
}

Step 2: Now, we write a Spring XML configuration file “spring.xml” and configure the bean defined above.

<!DOCTYPE beans PUBLIC


"-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
< beans>
<!--configure the bean HelloWorld.java
and declare its scope-->
< bean
id = "hw"
class = "bean.HelloWorld"
scope = "prototype" / >
</ beans>

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;

public class Client {

21
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science

public static void main(String[] args)


{
// Load the Spring XML configuration
// file into IoC container
ApplicationContext ap= new ClassPathXmlApplicationContext("resources/spring.xml");

// Get the "HelloWorld" bean object


// and call getName() method
HelloWorld Geeks1= (HelloWorld)ap.getBean("hw");

// Set the name


Geeks1.setName("Geeks1");

System.out.println("Hello object (hello1)"+ " Your name is: "+ Geeks1.getName());

// Get another "HelloWorld" bean object


// and call getName() method
HelloWorld Geeks2= (HelloWorld)ap.getBean("hw");

System.out.println("Hello object (hello2)"+ "Your name is: "+ Geeks2.getName());

// Now compare the references to see


// whether they are pointing to the
// same object or different object
System.out.println("'Geeks1' and 'Geeks2'"+ "are referring "+ "to the same object: "+ (Geeks1 ==
Geeks2));

// Print the address of both


// object Geeks1 and Geeks2
System.out.println("Address of object Geeks1: "+ Geeks1);
System.out.println("Address of object Geeks2: "+ Geeks2);
}
}

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

Difference between Singleton and Prototype

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.

The @RequestScope annotation works as a shortcut for @Scope(“request”) declaration.

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.

The @ApplicationScope annotation works as a shortcut for @Scope(“application”) declaration.

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

Autodetect The autodetect mode uses two other modes for


autowiring – constructor and byType

1. No

This mode tells the framework that autowiring is not supposed to be done. It is the default mode used by
Spring.

<bean id="state" class="sample.State">


<property name="name" value="UP" />
</bean>
<bean id="city" class="sample.City"></bean>

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.

<bean id="state" class="sample.State">


<property name="name" value="UP" />
</bean>
<bean id="city" class="sample.City" autowire="byName"></bean>

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.

<bean id="state" class="sample.State">


<property name="name" value="UP" />
</bean>
<bean id="city" class="sample.City" autowire="byType"></bean>

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.

<bean id="state" class="sample.State">


<property name="name" value="UP" />

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.

<bean id="state" class="sample.State">


<property name="name" value="UP" />
</bean>
<bean id="city" class="sample.City" autowire="autodetect"></bean>

Example of Autowiring

State.java

public class State {


private String name;
public String getName() { return name; }
public void setName(String s) { this.name = s; }
}

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

Spring bean configuration file:

<?xml version="1.0" encoding="UTF-8"?>


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="state" class="sample.State">
<property name="name" value="UP" />
</bean>
<bean id="city" class="sample.City" autowire="byName"></bean>
</beans>

Test Program file: DemoApplication.java

@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

Annotation Package Detail/Import statement


@Service import org.springframework.stereotype.Service;
@Repository import org.springframework.stereotype.Repository;
@Component import org.springframework.stereotype.Component;
@Autowired import org.springframework.beans.factory.annotation.Autowired;
@Transactional import org.springframework.transaction.annotation.Transactional;
@Scope import org.springframework.context.annotation.Scope;
Spring MVC Annotations
@Controller import org.springframework.stereotype.Controller;
@RequestMapping import org.springframework.web.bind.annotation.RequestMapping;
@PathVariable import org.springframework.web.bind.annotation.PathVariable;
@RequestParam import org.springframework.web.bind.annotation.RequestParam;
@ModelAttribute import org.springframework.web.bind.annotation.ModelAttribute;
@SessionAttributes import org.springframework.web.bind.annotation.SessionAttributes;
Spring Security Annotations
@PreAuthorize import org.springframework.security.access.prepost.PreAuthorize;

@Service

Annotate all your service classes with @Service. All your business logic should be in Service classes.

@Service

public class CompanyServiceImpl implements CompanyService {

...

@Repository

Annotate all your DAO classes with @Repository. All your database access logic should be in DAO classes.

@Repository

public class CompanyDAOImpl implements CompanyDAO {

...

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

public class ContactResource {

...

@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

public class CompanyServiceImpl implements CompanyService {

@Autowired

private CompanyDAO companyDAO;

31
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science

...

@Transactional

Configure your transactions with @Transactional spring annotation.

@Service

public class CompanyServiceImpl implements CompanyService {

@Autowired

private CompanyDAO companyDAO;

@Transactional

public Company findByName(String name) {

Company company = companyDAO.findByName(name);

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")

public class ContactResource {

...

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.

Spring bean Lifecycle Callbacks

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.

2. Using the lifecycle callbacks in <bean/> or @bean declarations.

3. Using the default initialization and destroy methods.

4. Startup and Shutdown callbacks from the Lifecycle interface

Spring Bean creation and destruction phases

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

Configuring a Bean in Spring / Spring Boot

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.

1. Configuring Beans in Spring / Spring Boot

There are multiple ways to configure beans in Spring and Spring Boot:

 Annotation-based Configuration: Annotations such as @Component, @Service, @Repository,


and @Controller are used to mark classes as Spring-managed beans. These annotations can be used to
automatically detect and register beans in the Spring application context.

 Java Configuration: Spring provides @Configuration and @Bean annotations to define beans using
Java configuration classes.

o @Configuration marks a class as a configuration class.

o @Bean is used to define individual beans.

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 [for Stereotype Annotations]

Annotation-based configuration is the most common approach used in modern Spring applications. When
Spring loads, Java beans are scanned in the following places:

 All @Bean definitions in @Configuration annotated classes

 If component scanning is enabled, all stereo-type annotated (such as @Component) classes

@Configuration

@ComponentScan(basePackages = "com.howtodoinjava.spring")

public class AppConfig {

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

public class EmployeeManager {

35
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science

public Employee create(Employee employee) {

//...

Now we can load the beans in context using AnnotationConfigApplicationContext as follows:

//Method 1

//ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);

//Method 2

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();

ctx.register(AppConfig.class);

ctx.refresh();

EmployeeManager empManager = ctx.getBean(EmployeeManager.class);

Employee emp = empManager.create();

3. Java Configuration [for @Bean Annotation]

Instead of annotating the classes with Spring annotations, we can declare them as Spring bean in the
configuration class:

@Configuration

public class AppConfig {

@Bean

public EmployeeManager employeeManager() {

return new EmployeeManager();

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

//ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);

//Method 2

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();

ctx.register(AppConfig.class);

ctx.refresh();

EmployeeManager empManager = ctx.getBean(EmployeeManager.class);

Employee emp = empManager.create();

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.

Why should we use Spring Boot Framework?

We should use Spring Boot Framework because:

o The dependency injection approach is used in Spring Boot.


o It contains powerful database transaction management capabilities.

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.

Advantages of Spring Boot

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.

Limitations of Spring Boot

Spring Boot can use dependencies that are not going to be used in the application. These dependencies increase
the size of the application.

What are annotations?

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.

Spring Boot annotation catagories


Based on the use case, Spring annotations fall in to one the following categories.

1. Bean definition annotations (from Core Spring Framework)


2. Configuration annotations
3. Spring Component annotations
4. Other modules Specific spring-boot annotations

1. Spring Core Annotations


These annotations are not part of spring boot but the spring framework itself. These annotations deal with
defining beans. So, Lets look at each of these in details.

@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) {

//create and return order Service


}
Code language: Java (java)
In the above scenario, all three beans must be defined for
the myServiceUsingAutowireMultiple factory method to succeed.

@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.

public class OrderService {

private PaymentService paymentService;

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)

2. Spring Boot Configuration annotations


Spring Boot favors java annotations over xml configurations. Even though both of them have pros and cons,
the annotations help create complex configurations that work dynamically. So lets go thorough each of these
with some examples.

@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

Code language: Java (java)

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

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.

Spring Boot Actuator Features

There are three main features of 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.

Enabling Spring Boot Actuator

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>

Spring Boot Actuator Endpoints

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.

The following table describes the widely used endpoints.

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

autoconfig It is used to display an auto-configuration report showing all auto- True


configuration candidates and the reason why they 'were' or 'were not'
applied.

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.

configprops It is used to display a collated list of all @ConfigurationProperties. True

dump It is used to perform a thread dump. True

env It is used to expose properties from Spring's ConfigurableEnvironment. True

flyway It is used to show any Flyway database migrations that have been True
applied.

health It is used to show application health information. False

info It is used to display arbitrary application info. False

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

mappings It is used to display a collated list of all @RequestMapping paths. True

shutdown It is used to allow the application to be gracefully shutdown. True

trace It is used to display trace information. True

For Spring MVC, the following additional endpoints are used.

Id Description Default

docs It is used to display documentation, including example requests and False


responses for the Actuator's endpoints.

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).

logfile It is used to return the contents of the logfile. True

45
S
U
D
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science

prometheus It is used to expose metrics in a format that can be scraped by a Tru


prometheus server. It requires a dependency on micrometer-registry-
prometheus.

Spring Boot - Build Systems


In Spring Boot, choosing a build system is an important task. We recommend Maven or Gradle as they
provide a good support for dependency management. Spring does not support well other build systems.

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')
}

Spring Boot - Code Structure


Spring Boot does not have any code layout to work with. However, there are some best practices that will
help us. This chapter talks about them in detail.

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);}
}

Spring Boot - Runners


Application Runner and Command Line Runner interfaces lets you to execute the code after the Spring Boot
application is started. You can use these interfaces to perform any actions immediately after the application
has started. This chapter talks about them in detail.

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

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 - Building RESTful Web Services

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 −

<?xml version = "1.0" encoding = "UTF-8"?>


<project xmlns = "http://maven.apache.org/POM/4.0.0"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">

<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}")
}
}

apply plugin: 'java'


apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

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);

Product almond = new Product();


almond.setId("2");
almond.setName("Almond");
productRepo.put(almond.getId(), almond);
}
@RequestMapping(value = "/products")
public ResponseEntity<Object> getProduct() {
return new ResponseEntity<>(productRepo.values(), HttpStatus.OK);
}
}

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<>();

@RequestMapping(value = "/products", method = RequestMethod.POST)


public ResponseEntity<Object> createProduct(@RequestBody Product product) {
productRepo.put(product.getId(), product);
return new ResponseEntity<>("Product is created successfully", HttpStatus.CREATED);
}
}

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

@RequestMapping(value = "/products/{id}", method = RequestMethod.PUT)


public ResponseEntity<Object> updateProduct(@PathVariable("id") String id, @RequestBody Product
product) {
productRepo.remove(id);
product.setId(id);
productRepo.put(id, product);
return new ResponseEntity<>("Product is updated successsfully", HttpStatus.OK);
}
}

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<>();

@RequestMapping(value = "/products/{id}", method = RequestMethod.DELETE)


public ResponseEntity<Object> delete(@PathVariable("id") String id) {
productRepo.remove(id);
return new ResponseEntity<>("Product is deleted successsfully", HttpStatus.OK);
}
}

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;

public class Product {


private String id;
private String name;

public String getId() {


return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The Rest Controller class – ProductServiceController.java
package com.tutorialspoint.demo.controller;

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);

Product almond = new Product();


almond.setId("2");
almond.setName("Almond");
productRepo.put(almond.getId(), almond);
}

@RequestMapping(value = "/products/{id}", method = RequestMethod.DELETE)


public ResponseEntity<Object> delete(@PathVariable("id") String id) {
productRepo.remove(id);
return new ResponseEntity<>("Product is deleted successsfully", HttpStatus.OK);
}

@RequestMapping(value = "/products/{id}", method = RequestMethod.PUT)


public ResponseEntity<Object> updateProduct(@PathVariable("id") String id, @RequestBody Product
product) {
productRepo.remove(id);
product.setId(id);
productRepo.put(id, product);
return new ResponseEntity<>("Product is updated successsfully", HttpStatus.OK);
}

@RequestMapping(value = "/products", method = RequestMethod.POST)


public ResponseEntity<Object> createProduct(@RequestBody Product product) {
productRepo.put(product.getId(), product);
return new ResponseEntity<>("Product is created successfully", HttpStatus.CREATED);
}

@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

return new ResponseEntity<>(productRepo.values(), HttpStatus.OK);


}
}

58
S
U
D

You might also like