0% found this document useful (0 votes)
19 views

Unit 5 Spring Framework

Uploaded by

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

Unit 5 Spring Framework

Uploaded by

ks881650
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 49

Unit 5 Spring Framework

Spring Framework


Spring is a lightweight framework.

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.

Advantages of Spring Framework



Predefined Templates
Spring framework provides templates for JDBC, Hibernate, JPA etc. technologies. So there is
no need to write too much code. It hides the basic steps of these technologies.

Loose Coupling
The Spring applications are loosely coupled because of dependency injection.

Easy to test
The Dependency Injection makes easier to test the application. The EJB or Struts application
require server to run the application but Spring frame work doesn't require server.


Lightweight
Spring framework is lightweight because of its POJO implementation. The Spring Framework
doesn't force the programmer to inherit any class or implement any interface. That is why
it is said non-invasive.

Fast Development
The Dependency Injection feature of Spring Framework and it support to various frameworks
makes the easy development of JavaEE application.

Powerful abstraction
It provides powerful abstraction to JavaEE specifications such as JMS, JDBC,JPA and JTA.

Declarative support
It provides declarative support for caching, validation, transactions and formatting.
Spring Core Concepts - DI, IoC, AOP
 Dependency Injection

 Inversion of Control.

 Aspect oriented programming

DI-Dependency Injection

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, an aspect of Inversion of Control (IOC), is a design pattern


to provide loose coupling. It removes the dependency from the program.

Without IOC & DI


public class
Employee{Address address;Employee()
{
address=newAddress(); //creating instance }}

Now, there is dependency between Employee and Address because Employee is


forced to use the same address instance.

With IOC & DI

public class
Employee{Address address;
Employee(Address address)
{this.address=address; //not creating instance }}

Now, there is no dependency between Employeeand Address because Employee


is not forced to use the same address instance. It can use anyaddress instance.

Inversion Of Control (IOC)



IOC makes the code loosely coupled. In such case, there is no need to modify the code if our
logic is moved to new environment.

In Spring framework, IOC container is responsible to inject the dependency.

We provide metadata to the IOC container either by XML file or annotation.

Advantage of Dependency Injection:

1 Makes the code loosely coupled so easy to maintain

2 Makes the code easy to test

IoC Container
The IoC container is responsible to instantiate, configure and assemble the objects.
The IoC container gets information’s from the XML file and works accordingly. The
main tasks performed by IoC container are:

o to instantiate the application class


o to configure the object
o to assemble the dependencies between the objects

There are two types of IoC containers. They are:

1. BeanFactory
2. ApplicationContext

Difference between BeanFactory and the ApplicationContext


The org.springframework.beans.factory.BeanFactory

and the org.springframework.context.ApplicationContext

interfaces acts as the IoC container. The ApplicationContext interface is built on top of
the BeanFactory interface. It adds some extra functionality than BeanFactory such as
simple integration with Spring's AOP, message resource handling (for I18N), event
propagation, application layer specific context (e.g. WebApplicationContext) for web
application. So it is better to use ApplicationContext than BeanFactory.

Using BeanFactory
The XmlBeanFactory is the implementation class for the BeanFactory interface. To use
the BeanFactory, we need to create the instance of XmlBeanFactory class as given
below:

1. Resource resource=new ClassPathResource("applicationContext.xml");


2. BeanFactory factory=new XmlBeanFactory(resource);
The constructor of XmlBeanFactory class receives the Resource object so we need to
pass the resource object to create the object of BeanFactory.

Using ApplicationContext
The ClassPathXmlApplicationContext class is the implementation class of
ApplicationContext interface. We need to instantiate the
ClassPathXmlApplicationContext class to use the ApplicationContext as given below:

1. ApplicationContext context =
2. new ClassPathXmlApplicationContext("applicationContext.xml");

The constructor of ClassPathXmlApplicationContext class receives string, so we can


pass the name of the xml file to create the instance of ApplicationContext.

Two ways to perform Dependency Injection in Spring framework


Spring framework provides two ways to inject dependency

o By Constructor
o By Setter method

Dependency Injection by Constructor Example


1. Dependency Injection by constructor
2. Injecting primitive and string-based values

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


Let's see the simple example 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.

1. package com.javatpoint;
2.
3. public class Employee {
4. private int id;
5. private String name;
6.
7. public Employee() {System.out.println("def cons");}
8.
9. public Employee(int id) {this.id = id;}
10.
11.public Employee(String name) { this.name = name;}
12.
13.public Employee(int id, String name) {
14. this.id = id;
15. this.name = name;
16.}
17.
18.void show(){
19. System.out.println(id+" "+name);
20.}
21.

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.

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


2. <beans
3. xmlns="http://www.springframework.org/schema/beans"
4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5. xmlns:p="http://www.springframework.org/schema/p"
6. xsi:schemaLocation="http://www.springframework.org/schema/beans
7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
8.
9. <bean id="e" class="com.javatpoint.Employee">
10.<constructor-arg value="10" type="int"></constructor-arg>
11.</bean>
12.
13.</beans>

Test.java

This class gets the bean from the applicationContext.xml file and calls the show
method.

1. package com.javatpoint;
2.
3. import org.springframework.beans.factory.BeanFactory;
4. import org.springframework.beans.factory.xml.XmlBeanFactory;
5. import org.springframework.core.io.*;
6.
7. public class Test {
8. public static void main(String[] args) {
9.
10. Resource r=new ClassPathResource("applicationContext.xml");
11. BeanFactory factory=new XmlBeanFactory(r);
12.
13. Employee s=(Employee)factory.getBean("e");
14. s.show();
15.
16. }
17.}

Output:10 null

Dependency Injection by setter method


1. Dependency Injection by constructor
2. Injecting primitive and string-based values

We can inject the dependency by setter method also. The <property> subelement
of <bean> is used for setter 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 by setter method


Let's see the simple example to inject primitive and string-based values by setter
method. We have created three files here:

o Employee.java
o applicationContext.xml
o Test.java

Employee.java

It is a simple class containing three fields id, name and city with its setters and getters
and a method to display these informations.

1. package com.javatpoint;
2.
3. public class Employee {
4. private int id;
5. private String name;
6. private String city;
7.
8. public int getId() {
9. return id;
10.}
11.public void setId(int id) {
12. this.id = id;
13.}
14.public String getName() {
15. return name;
16.}
17.public void setName(String name) {
18. this.name = name;
19.}
20.
21.public String getCity() {
22. return city;
23.}
24.public void setCity(String city) {
25. this.city = city;
26.}
27.void display(){
28. System.out.println(id+" "+name+" "+city);
29.}
30.
31.}

applicationContext.xml

We are providing the information into the bean by this file. The property element
invokes the setter method. The value subelement of property will assign the specified
value.

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


2. <beans
3. xmlns="http://www.springframework.org/schema/beans"
4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5. xmlns:p="http://www.springframework.org/schema/p"
6. xsi:schemaLocation="http://www.springframework.org/schema/beans
7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
8.
9. <bean id="obj" class="com.javatpoint.Employee">
10.<property name="id">
11.<value>20</value>
12.</property>
13.<property name="name">
14.<value>Arun</value>
15.</property>
16.<property name="city">
17.<value>ghaziabad</value>
18.</property>
19.
20.</bean>
21.
22.</beans>

Test.java

This class gets the bean from the applicationContext.xml file and calls the display
method.

1. package com.javatpoint;
2.
3. import org.springframework.beans.factory.BeanFactory;
4. import org.springframework.beans.factory.xml.XmlBeanFactory;
5. import org.springframework.core.io.*;
6.
7. public class Test {
8. public static void main(String[] args) {
9.
10. Resource r=new ClassPathResource("applicationContext.xml");
11. BeanFactory factory=new XmlBeanFactory(r);
12.
13. Employee e=(Employee)factory.getBean("obj");
14. s.display();
15.
16. }
17.}

Output:20 Arun Ghaziabad

Spring AOP
Aspect Oriented Programming (AOP) compliments OOPs in the sense that it also
provides modularity. But the key unit of modularity is aspect than class.

AOP breaks the program logic into distinct parts (called concerns). It is used to
increase modularity by cross-cutting concerns.

A cross-cutting concern is a concern that can affect the whole application and
should be centralized in one location in code as possible, such as transaction
management, authentication, logging, security etc.

Why use AOP?

It provides the pluggable way to dynamically add the additional concern before, after
or around the actual logic. Suppose there are 10 methods in a class as given below:

1. class A{
2. public void m1(){...}
3. public void m2(){...}
4. public void m3(){...}
5. public void m4(){...}
6. public void m5(){...}
7. public void n1(){...}
8. public void n2(){...}
9. public void p1(){...}
10.public void p2(){...}
11.public void p3(){...}
12.}

There are 5 methods that starts from m, 2 methods that starts from n and 3 methods
that starts from p.

Understanding Scenario I have to maintain log and send notification after calling
methods that starts from m.

Problem without AOP We can call methods (that maintains log and sends
notification) from the methods starting with m. In such scenario, we need to write the
code in all the 5 methods.

But, if client says in future, I don't have to send notification, you need to change all
the methods. It leads to the maintenance problem.

Solution with AOP We don't have to call methods from the method. Now we can
define the additional concern like maintaining log, sending notification etc. in the
method of a class. Its entry is given in the xml file.

In future, if client says to remove the notifier functionality, we need to change only in
the xml file. So, maintenance is easy in AOP.

Where use AOP?

AOP is mostly used in following cases:

o to provide declarative enterprise services such as declarative transaction management.


o It allows users to implement custom aspects.

AOP Concepts and Terminology


AOP concepts and terminologies are as follows:

o Join point
o Advice
o Pointcut
o Introduction
o Target Object
o Aspect
o Interceptor
o AOP Proxy
o Weaving

Join point

Join point is any point in your program such as method execution, exception handling,
field access etc. Spring supports only method execution join point.

Advice

Advice represents an action taken by an aspect at a particular join point. There are
different types of advices:

o Before Advice: it executes before a join point.


o After Returning Advice: it executes after a joint point completes normally.
o After Throwing Advice: it executes if method exits by throwing an exception.
o After (finally) Advice: it executes after a join point regardless of join point exit
whether normally or exceptional return.
o Around Advice: It executes before and after a join point.

Pointcut

It is an expression language of AOP that matches join points.

Introduction

It means introduction of additional method and fields for a type. It allows you to
introduce new interface to any advised object.

Target Object

It is the object i.e. being advised by one or more aspects. It is also known as proxied
object in spring because Spring AOP is implemented using runtime proxies.

Aspect

It is a class that contains advices, joinpoints etc.


Interceptor

It is an aspect that contains only one advice.

AOP Proxy

It is used to implement aspect contracts, created by AOP framework. It will be a JDK


dynamic proxy or CGLIB proxy in spring framework.

Weaving

It is the process of linking aspect with other application types or objects to create an
advised object. Weaving can be done at compile time, load time or runtime. Spring
AOP performs weaving at runtime.

What are Spring beans

The Spring Beans are Java Objects that form the backbone of a Spring application.
They are instantiated, assembled, and managed by the Spring IoC container.
These beans are created with the configuration metadata that is supplied to the
container, for example, in the form of XML <bean/> definitions. Beans defined in
spring framework are singleton beans. There is an attribute in bean tag named
"singleton" if specified true then bean becomes singleton and if set to false then
the bean becomes a prototype bean. By default it is set to true. So, all the beans in
spring framework are by default singleton beans.

Singleton and Prototype 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.
Let’s us see some of them in detail:

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.
Let’s understand this scope with an example.

 Step1: Lets first create a bean (i.e.), the backbone of the application in the spring
framework.
 Java

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

<!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 = "singleton" / >

</beans>

 Step 3: Finally, write a driver class “Client.java” to request the above bean.
 Java

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

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

 Output:
Hello object (hello1) Your name is: Geeks1
Hello object (hello2) Your name is: Geeks1
'Geeks1' and 'Geeks2' are referring to the same object: true
Address of object Geeks1: bean.HelloWorld@627551fb
Address of object Geeks2: bean.HelloWorld@627551fb
 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.
Let’s understand this scope with an example:

 Step 1: Let us first create a bean (i.e.), the backbone of the application in the
spring framework.

 Java

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

 XML

<!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

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

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

 Output:
Hello object (hello1) Your name is: Geeks1
Hello object (hello2) Your name is: null
'Geeks1' and 'Geeks2' are referring to the same object: false
Address of object Geeks1: bean.HelloWorld@47ef968d
Address of object Geeks2: bean.HelloWorld@23e028a9
 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.

Difference between Singleton and Prototype

Singleton Prototype

A new instance is created for a single bean


Only one instance is created for a single bean
definition every time a request is made for
definition per Spring IoC container
that bean.

Same object is shared for each request made for For each new request a new instance is
that bean. i.e. The same object is returned each created. i.e. A new object is created each time
time it is injected. it is injected.

By default scope is not prototype so you have


By default scope of a bean is singleton. So we don’t
to declare the scope of a been as prototype
need to declare a been as singleton explicitly.
explicitly.

While prototype scope is used for all beans


Singleton scope should be used for stateless beans.
that are stateful

Spring - Bean Life Cycle

The life cycle of a Spring bean is easy to understand. When a bean is


instantiated, it may be required to perform some initialization to get it into a
usable state. Similarly, when the bean is no longer required and is removed
from the container, some cleanup may be required.

Though, there are lists of the activities that take place behind the scene
between the time of bean Instantiation and its destruction, this chapter will
discuss only two important bean life cycle callback methods, which are
required at the time of bean initialization and its destruction.
To define setup and teardown for a bean, we simply declare the <bean>
with initmethod and/or destroy-method parameters. The init-method
attribute specifies a method that is to be called on the bean immediately
upon instantiation. Similarly, destroymethod specifies a method that is
called just before a bean is removed from the container.

Initialization callbacks
The org.springframework.beans.factory.InitializingBean interface specifies a
single method −

void afterPropertiesSet() throws Exception;

Thus, you can simply implement the above interface and initialization work
can be done inside afterPropertiesSet() method as follows −

public class ExampleBean implements InitializingBean {


public void afterPropertiesSet() {
// do some initialization work
}
}
In the case of XML-based configuration metadata, you can use the init-
method attribute to specify the name of the method that has a void no-
argument signature. For example −
<bean id = "exampleBean" class = "examples.ExampleBean" init-method = "init"/>

Following is the class definition −

public class ExampleBean {


public void init() {
// do some initialization work
}
}

Destruction callbacks
The org.springframework.beans.factory.DisposableBean interface specifies a
single method −
void destroy() throws Exception;

Thus, you can simply implement the above interface and finalization work
can be done inside destroy() method as follows −

public class ExampleBean implements DisposableBean {


public void destroy() {
// do some destruction work
}
}
In the case of XML-based configuration metadata, you can use the destroy-
method attribute to specify the name of the method that has a void no-
argument signature. For example −
<bean id = "exampleBean" class = "examples.ExampleBean" destroy-method =
"destroy"/>

Following is the class definition −

public class ExampleBean {


public void destroy() {
// do some destruction work
}
}

If you are using Spring's IoC container in a non-web application


environment; for example, in a rich client desktop environment, you register
a shutdown hook with the JVM. Doing so ensures a graceful shutdown and
calls the relevant destroy methods on your singleton beans so that all
resources are released.

It is recommended that you do not use the InitializingBean or


DisposableBean callbacks, because XML configuration gives much flexibility
in terms of naming your method.

Example

Let us have a working Eclipse IDE in place and take the following steps to
create a Spring application −

Ste
Description
ps

Create a project with a name SpringExample and create a


1
package com.tutorialspoint under the src folder in the created project.

Add required Spring libraries using Add External JARs option as explained in
2
the Spring Hello World Example chapter.

Create Java classes HelloWorld and MainApp under


3
the com.tutorialspoint package.

4 Create Beans configuration file Beans.xml under the src folder.

The final step is to create the content of all the Java files and Bean Configuration
5
file and run the application as explained below.

Here is the content of HelloWorld.java file −


package com.tutorialspoint;

public class HelloWorld {


private String message;

public void setMessage(String message){


this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
public void init(){
System.out.println("Bean is going through init.");
}
public void destroy() {
System.out.println("Bean will destroy now.");
}
}
Following is the content of the MainApp.java file. Here you need to register
a shutdown hook registerShutdownHook() method that is declared on the
AbstractApplicationContext class. This will ensure a graceful shutdown and
call the relevant destroy methods.
package com.tutorialspoint;

import
org.springframework.context.support.AbstractApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationConte
xt;

public class MainApp {


public static void main(String[] args) {
AbstractApplicationContext context = new
ClassPathXmlApplicationContext("Beans.xml");

HelloWorld obj = (HelloWorld)


context.getBean("helloWorld");
obj.getMessage();
context.registerShutdownHook();
}
}
Following is the configuration file Beans.xml required for init and destroy
methods −
<?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
http://www.springframework.org/schema/beans/spring-beans-
3.0.xsd">

<bean id = "helloWorld" class =


"com.tutorialspoint.HelloWorld" init-method = "init"
destroy-method = "destroy">
<property name = "message" value = "Hello World!"/>
</bean>

</beans>

Once you are done creating the source and bean configuration files, let us
run the application. If everything is fine with your application, it will print the
following message −

Bean is going through init.


Your Message : Hello World!
Bean will destroy now.

Default initialization and destroy methods


If you have too many beans having initialization and/or destroy methods
with the same name, you don't need to declare init-method and destroy-
method on each individual bean. Instead, the framework provides the
flexibility to configure such situation using default-init-
method and default-destroy-method attributes on the <beans> element
as follows −
<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
http://www.springframework.org/schema/beans/spring-beans-
3.0.xsd"
default-init-method = "init"
default-destroy-method = "destroy">

<bean id = "..." class = "...">


<!-- collaborators and configuration for this bean go here
-->
</bean>
</beans>

What is autowiring in spring? What are the autowiringmodes


Autowiring enables the programmer to inject the bean automatically. We
don'tneed to write explicit injection logic. Let's see the code to inject bean
usingdependency injection.
<bean id="emp" class="com.javatpoint.Employee" autowire="byName" />

Spring Web Socket




WebSocket is used as a communication protocol that provides full-duplex


communication channels over a single, long-lived connection between a
client and a server. In this protocol, there are no restrictions like HTTP that
for a response you have to make a request first.
The server can send the message without getting any request and this can
be useful in many applications like
 Chat applications
 Sending any notification to the user
 And many more.
Why WebSocket is used Over HTTP?
In HTTP client has to request only the response or the payload from the
server will be given and then the connection is terminated. Now if you
require further payload or data then you have to repeat the whole process.
 WebSocket client establishes the socket connection with the server and
receives the message or data without any refresh
 The connection won’t be terminated which means that we can again
receive the message.
Also, WebSocket is a bi-directional protocol which means that the server and
client can exchange the message in parallel and it decreases the round
trip and the time for response. An application like trading, monitoring, or
creating functionality like notifications WebSocket is very useful.

Spring Framework Annotations

Spring framework is one of the most popular Java EE frameworks. It 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 you manage your business objects. Now talking about
Spring Annotation, Spring Annotations are a form of metadata that provides data
about a program. Annotations are used to provide supplemental information about a
program. It does not have a direct effect on the operation of the code they annotate. It
does not change the action of the compiled program. So in this article, we are going to
discuss what are the main types of annotation that are available in the spring
framework with some examples.
Types of Spring Framework Annotations
Basically, there are 6 types of annotation available in the whole spring framework.
1. Spring Core Annotations
2. Spring Web Annotations
3. Spring Boot Annotations
4. Spring Scheduling Annotations
5. Spring Data Annotations
6. Spring Bean Annotations

Type 1: Spring Core Annotations


Spring annotations present in
the org.springframework.beans.factory.annotation and org.springframework.con
text.annotation packages are commonly known as Spring Core annotations. We can
divide them into two categories:
 DI-Related Annotations
o @Autowired
o @Qualifier
o @Primary
o @Bean
o @Lazy
o @Required
o @Value
o @Scope
o @Lookup, etc.
 Context Configuration Annotations
o @Profile
o @Import
o @ImportResource
o @PropertySource, etc.
A DI (Dependency Injection) Related Annotations
1.1: @Autowired
@Autowired annotation is applied to the fields, setter methods, and constructors. It
injects object dependency implicitly. We use @Autowired to mark the dependency
that will be injected by the Spring container.
1.2: Field injection
 Java

class Student {

@Autowired

Address address;

1.3: Constructor injection


 Java

class Student {

Address address;

@Autowired

Student(Address address) {

this.address = address;

1.4: Setter injection


 Java

class Student {

Address address;
@Autowired

void setaddress(Address address) {

this.address = address;

B Context Configuration Annotations


@Profile: If you want Spring to use a @Component class or a @Bean method only
when a specific profile is active then you can mark it with @Profile.
@Component
@Profile("developer")
public class Employee {}
Type 2: Spring Web Annotations
Spring annotations present in the org.springframework.web.bind.annotation
packages are commonly known as Spring Web annotations. Some of the annotations
that are available in this category are:
 @RequestMapping
 @RequestBody
 @PathVariable
 @RequestParam
 Response Handling Annotations
o @ResponseBody
o @ExceptionHandler
o @ResponseStatus
 @Controller
 @RestController
 @ModelAttribute
 @CrossOrigin
Example: @Controller
Spring @Controller annotation is also a specialization of @Component annotation.
The @Controller annotation indicates that a particular class serves the role of a
controller. Spring Controller annotation is typically used in combination with annotated
handler methods based on the @RequestMapping annotation. It can be applied to
classes only. It’s used to mark a class as a web request handler. It’s mostly used with
Spring MVC applications. This annotation acts as a stereotype for the annotated
class, indicating its role. The dispatcher scans such annotated classes for mapped
methods and detects @RequestMapping annotations.
 Java

package com.example.demo.controller;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

@Controller

public class DemoController {

@RequestMapping("/hello")

@ResponseBody

public String helloGFG()

return "Hello GeeksForGeeks";

Type 3: Spring Boot Annotations


Spring annotations present in
the org.springframework.boot.autoconfigure and org.springframework.boot.auto
configure.condition packages are commonly known as Spring Boot annotations.
Some of the annotations that are available in this category are:
 @SpringBootApplication
 @EnableAutoConfiguration
 Auto-Configuration Conditions
o @ConditionalOnClass, and @ConditionalOnMissingClass
o @ConditionalOnBean, and @ConditionalOnMissingBean
o @ConditionalOnProperty
o @ConditionalOnResource
@ConditionalOnWebApplication and @ConditionalOnNotWebApplication
o
o @ConditionalExpression
o @Conditional
Example: @SpringBootApplication
This annotation is used to mark the main class of a Spring Boot application. It
encapsulates @Configuration, @EnableAutoConfiguration, and @ComponentScan
annotations with their default attributes.

 Java

@SpringBootApplication

// Class

public class DemoApplication {

// Main driver method

public static void main(String[] args)

SpringApplication.run(DemoApplication.class, args);

Type 4: Spring Scheduling Annotations


Spring annotations present in
the org.springframework.scheduling.annotation packages are commonly known
as Spring Scheduling annotations. Some of the annotations that are available in this
category are:
 @EnableAsync
 @EnableScheduling
 @Async
 @Scheduled
 @Schedules
Example: @EnableAsync
This annotation is used to enable asynchronous functionality in Spring.
@Configuration
@EnableAsync
class Config {}
Type 5: Spring Data Annotations
Spring Data provides an abstraction over data storage technologies. Hence the
business logic code can be much more independent of the underlying persistence
implementation. Some of the annotations that are available in this category are:
 Common Spring Data Annotations
o @Transactional
o @NoRepositoryBean
o @Param
o @Id
o @Transient
o @CreatedBy, @LastModifiedBy, @CreatedDate, @LastModifiedDate
 Spring Data JPA Annotations
o @Query
o @Procedure
o @Lock
o @Modifying
o @EnableJpaRepositories
 Spring Data Mongo Annotations
o @Document
o @Field
o @Query
o @EnableMongoRepositories
Example:
A @Transactional
When there is a need to configure the transactional behavior of a method, we can do
it with @Transactional annotation.
@Transactional
void payment() {}
B @Id: @Id marks a field in a model class as the primary key. Since it’s
implementation-independent, it makes a model class easy to use with multiple data
store engines.
class Student {

@Id
Long id;

// other fields
// ...........

}
Type 6: Spring Bean Annotations
There’re several ways to configure beans in a Spring container. You can declare them
using XML configuration or you can declare beans using the @Bean annotation in a
configuration class or you can mark the class with one of the annotations from
the org.springframework.stereotype package and leave the rest to component
scanning. Some of the annotations that are available in this category are:
 @ComponentScan
 @Configuration
 Stereotype Annotations
o @Component
o @Service
o @Repository
o @Controller
Example: Stereotype Annotations
Spring Framework provides us with some special annotations. These annotations are
used to create Spring beans automatically in the application context. @Component
annotation is the main Stereotype Annotation. There are some Stereotype meta-
annotations which is derived from @Component those are
1. @Service
2. @Repository
3. @Controller
1: @Service: We specify a class with @Service to indicate that they’re holding the
business logic. Besides being used in the service layer, there isn’t any other special
use for this annotation. The utility classes can be marked as Service classes.
2: @Repository: We specify a class with @Repository to indicate that they’re dealing
with CRUD operations, usually, it’s used with DAO (Data Access Object) or
Repository implementations that deal with database tables.
3: @Controller: We specify a class with @Controller to indicate that they’re front
controllers and responsible to handle user requests and return the appropriate
response. It is mostly used with REST Web Services.
So the stereotype annotations in spring are @Component, @Service, @Repository,
and @Controller.

How to Create a Spring Bean in 3 Different Ways



Spring is one of the most popular Java EE frameworks. It 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 you manage your business objects. It
made the development of Web applications much easier than compared to
classic Java frameworks and application programming interfaces (APIs), such
as Java database connectivity (JDBC), JavaServer Pages(JSP), and Java
Servlet. In Spring, the objects that form the backbone of your 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.

Different Methods to Create a Spring Bean

Here we are going to discuss how to create a Spring Bean in 3 different ways
as follows:
1. Creating Bean Inside an XML Configuration File (beans.xml)
2. Using @Component Annotation
3. Using @Bean Annotation

Method 1: Creating Bean Inside an XML Configuration File


(beans.xml)

One of the most popular ways to create a spring bean is to define a bean in
an XML configuration file something like this.
<bean id="AnyUniqueId" class="YourClassName">
</bean>
Let us create a simple class Student having two attributes id and
studentName and later creating a simple method to print the details of the
student.
Example
 Java

// Java Program to Illustrate Student Class

// Class

public class Student {


// Class data members

private int id;

private String studentName;

// Method

public void displayInfo()

// Print statement

System.out.println("Student Name is " + studentName

+ " and Roll Number is " + id);

Now let’s create an XML file named beans.xml file in the project classpath.
And inside this beans.xml file, we have to define our Student bean
something like this. And that’s it. In this way, you can create beans in
spring.
Example
 XML

<?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="studentAmiya" class="Student">

</bean>

</beans>

Method 2: Using @Component Annotation

Spring Annotations are a form of metadata that provides data about a


program. Annotations are used to provide supplemental information about a
program. It does not have a direct effect on the operation of the code they
annotate. It does not change the action of the compiled
program. @Component is an annotation that allows Spring to automatically
detect the custom beans.
Example: Suppose we have already a Java project and all the Spring JAR
files are imported into that project. Now let’s create a simple class named
College and inside the class, we have a simple method. Below is the code for
the College.java file.
A. File: College.java
 Java

// Java Program to Illustrate College Class

package ComponentAnnotation;

// Class

public class College {


// Method

public void test()

// Print statement

// whenever this method is called

System.out.println("Test College Method");

Now let’s create a Bean for this class. So we can


use @Component annotation for doing the same task. So we can modify
our College.java file something like this. And that’s it.
B. College.java
 Java

// Java Program to Illustrate College Class

package ComponentAnnotation;

// Importing required classes

import org.springframework.stereotype.Component;

@Component("collegeBean")
// Class

public class College {

// Method

public void test()

// Print statement

System.out.println("Test College Method");

Method 3: Using @Bean Annotation

One of the most important annotations in spring is the @Bean


annotation which is applied on a method to specify that it returns a bean to
be managed by Spring context. Spring Bean annotation is usually declared
in Configuration classes methods.
Suppose we have already a Java project and all the Spring JAR files are
imported into that project. Now let’s create a simple class named College
and inside the class, we have a simple method. Below is the code for
the College.java file.
A. College.java
 Java

package BeanAnnotation;

import org.springframework.stereotype.Component;
public class College {

public void test(){

System.out.println("Test College Method");

Now let’s create a Configuration class named CollegeConfig. Below is the


code for the CollegeConfig.java file
B. CollegeConfig.java
 Java

package ComponentAnnotation;

import org.springframework.context.annotation.ComponentScan;

import org.springframework.context.annotation.Configuration;

@Configuration

public class CollegeConfig {

Here, we are going to create the spring beans using the @Bean
annotation. To create the College class bean using the @Bean annotation
inside the configuration class we can write something like this inside
our CollegeConfig.java file. Please refer to the comments for a better
understanding.
@Bean
// Here the method name is the
// bean id/bean name
public College collegeBean(){
// Return the College object
return new College();
}
Implementation: Below is the complete code for
the CollegeConfig.java file that is below as follows:
 Java

// Java Program to Illustrate Configuration in College Class

package BeanAnnotation;

// Importing required classes

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

@Configuration

public class CollegeConfig {

// Using Bean annotation to create

// College class Bean

@Bean

// Here the method name is the

// bean id/bean name


public College collegeBean()

// Return the College object

return new College();

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.


 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.
Let’s explore each method in detail:

2. 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 {


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

}
}

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.

4.1. Bean Definitions


When using XML files, we can define the beans either in a single file or we
can distribute the beans in separate files for better code structure. Either
way, the bean definitions will be created the same.

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

<beans>

<bean id="operations" class="com.howtodoinjava.core.demo.beans.Operations"></bean>

<bean id="employee" class="com.howtodoinjava.core.demo.beans.Employee"></bean>

<bean id="department" class="com.howtodoinjava.core.demo.beans.Department"></bean>

</beans>
If we have created multiple bean definition files, we can import the files in
the current file as follows:

<beans>

<import resource="employee.xml"/>

<import resource="department.xml"/>

<bean id="operations" class="com.howtodoinjava.spring.beans.Operations"></bean>

</beans>

4.2. Loading Beans into Context


To load the bean definitions files and thus initialize beans, we can pass the
bean definition file name into the constructor of any one of
the ApplicationContext implementations.

 ClassPathXmlApplicationContext
 FileSystemXmlApplicationContext
 XmlWebApplicationContext
Following is an example of loading the beans.xml file
into ClassPathXmlApplicationContext. Note that the bean definition file is
located at '/src/main/resources/beans.xml'.

ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:beans.xml");

Employee employee = ctx.getBean(Employee.class);

Department department = ctx.getBean(Department.class);

Operations operations = ctx.getBean(Operations.class);

Program output:
Jan 02, 2018 3:10:27 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions

INFO: Loading XML bean definitions from class path resource [beans.xml]

Jan 02, 2018 3:10:27 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions

INFO: Loading XML bean definitions from class path resource [employee.xml]

Jan 02, 2018 3:10:27 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions

INFO: Loading XML bean definitions from class path resource [department.xml]

5. When to Use Each Method


 Annotation-based Configuration: Use this approach for most cases
in modern Spring / Spring Boot applications. It’s concise, easy to read,
and promotes convention over configuration.
 Java Configuration: Use Java configuration when you need more
control over bean creation, or when you want to use features like
conditional bean registration.
 XML Configuration: Use XML configuration for legacy applications or
when working with frameworks that require XML configuration.

6. Conclusion
Configuring beans in Spring and Spring Boot is a fundamental aspect of
application development. Understanding the different ways to configure
beans and when to use each method is essential for building maintainable
and scalable applications.

Whether you prefer annotation-based configuration, Java configuration, or


XML configuration, Spring provides flexible options to suit your needs.
Choose the approach that best fits your project requirements and
development style.

You might also like