Spring Framework
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
• Representational State Transfer (REST) is an
architectural style that defines a set of
constraints to be used for creating web
services.
• REST API is a way of accessing web services in
a simple and flexible way without having any
processing.
BCS 403 By Surendra Kumar, AP AKGEC
• Spring HATEOAS is a module that helps you create REST
representations that follow the HATEOAS [Link]
use Spring HATEOAS, you need to:Add the spring-
boot-starter-hateoas module to your Spring Boot
project.
• Use the API to create and insert links in the REST
responses.
• Examples of using Spring HATEOAS include:Building
HATEOAS hyperlinks based on a method of a class.
• Creating a Book entity that demonstrates HATEOAS.
• Creating a Spring web MVC application providing
albums and their actors’ basic information.
BCS 403 By Surendra Kumar, AP AKGEC
why
BCS 403 By Surendra Kumar, AP AKGEC
Why popular
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
Spring Object XML Mappers
JMS (Java Message Service)
BCS 403 By Surendra Kumar, AP AKGEC
What is MVC?
The Model-View-Controller (MVC) framework is an architectural/design pattern that separates
an application into three main logical components Model, View, and Controller.
Each architectural component is built to handle specific development aspects of an
application. It isolates the business logic and presentation layer from each other. It was
traditionally used for desktop graphical user interfaces (GUIs).
Nowadays, MVC is one of the most frequently used industry-standard web development
frameworks to create scalable and extensible projects. It is also used for designing mobile
apps. BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
Client class
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
Context Container
BCS 403 By Surendra Kumar, AP AKGEC
Comment other exccept
ApplicaitonContext
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
Bean
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
Close context
BCS 403 By Surendra Kumar, AP AKGEC
Demo on bean
BCS 403 By Surendra Kumar, AP AKGEC
High dependency
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
Loose dependency
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
Write another class Address
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
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
1. Struts (MVC-based web application), The Model-View-Controller (MVC) is a
well-known design pattern in the web development field.
It is way to organize our code.
It specifies that a program or application shall consist of data model,
presentation information and control information.
2. Hibernate(Hibernate is a Java framework that simplifies the
development of Java application to interact with the database.
– It is an open source, lightweight, ORM (Object Relational Mapping)
tool.
– Hibernate implements the specifications of JPA (Java Persistence API): It
is a middleware application or tool that sits between the web
application and database.
– It wraps the implementation specific
BCS 403 By Surendra Kumar,details
AP AKGEC of storage drivers in an API.
Hibernate
• Hibernate is a Java persistence framework that simplifies the
development of Java application to interact with the database.
• It is an open source, widely used, lightweight, ORM tool. Hibernate
implements the specifications of JPA (Java Persistence API) for data
persistence.
Advantages of Hibernate
• It is an open source, lightweight, flexible, and powerful ORM tool.
• It supports database independent query (HQL).
• Its performance is fast because cache is internally used.
• It simplifies the complex join.
• If there is any modification in table or database only need to change
in XML file properties.
BCS 403 By Surendra Kumar, AP AKGEC
– What is ORM?
• ORM is a technique for converting data
between Java objects and relational
databases (table).
• In simple words, we can say that
the ORM implements responsibility of
mapping the object to relational
model and vice-versa.
• The ORM tool does mapping in such a
way that model class becomes a table
in the database and each instance
becomes a row of the table. for data
persistence.)
BCS 403 By Surendra Kumar, AP AKGEC
Advantages of ORM Tool
• It saves time and efforts.
• It gives pace to development process.
• It reduces the development cost.
• It provides connectivity to the database.
• It makes development more object-oriented.
• Easy transaction management.
• No need to implement database manually.
• Modification in any model (object or relational model) does not affect
each other.
BCS 403 By Surendra Kumar, AP AKGEC
ORM Tools
There are many ORM tools available but the following ORM tools are the
most commonly used.
– Hibernate
– TopLink
– EclipseLink
– OpenJPA
– MyBatis (formally known as iBatis)
BCS 403 By Surendra Kumar, AP AKGEC
3. Tapestry (Tapestry easily integrates with Spring Framework, allowing beans
defined by Spring to be injected into Tapestry IoC services, and into Tapestry
components.
In addition, with Tapestry 5.2 and later, you can also go the other way, injecting
Tapestry services in Spring beans.)
4. EJB (EJB (Enterprise Java Bean) is used to develop scalable, robust and
secured enterprise applications in java.
Unlike RMI, middleware services such as security, transaction management etc.
are provided by EJB Container to all EJB applications.)
BCS 403 By Surendra Kumar, AP AKGEC
5. JSF (JSF stands for Java Server Faces).
It is a server-side Java framework for web development.
includes all topics of JSF such as features, example, validation, bean validation,
managed bean, referencing managed bean method, facelets etc) etc.
The framework, in broader sense, can be defined as a structure where we find
solution of the various technical problems.
BCS 403 By Surendra Kumar, AP AKGEC
• The Spring framework comprises several modules such as
– IOC (Inversion Of Control )
– AOP (Aspect Oriented Programming )
– DAO (Data Access Object )
– Context,
– ORM, (Object-relational mapping)
– WEB MVC (Model-View-Controller ) etc.
BCS 403 By Surendra Kumar, AP AKGEC
Bean Definition
• 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.
BCS 403 By Surendra Kumar, AP AKGEC
Advantages of Spring Framework
There are many advantages of Spring Framework. They are as follows:
1) 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.
Let's take the example of JdbcTemplate, you don't need to write the code for
exception handling, creating connection, creating statement, committing
transaction, closing connection etc. You need to write the code of executing
query only. Thus, it save a lot of JDBC code.
2) Loose Coupling
The Spring applications are loosely coupled because of dependency injection.
3) 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 framework
doesn't require server.
BCS 403 By Surendra Kumar, AP AKGEC
Inversion Of Control (IOC) and
Dependency Injection
These are the design patterns that are used to remove dependency from the programming code.
They make the code easier to test and maintain. Let's understand this with the following code:
class Employee{
Address address;
Employee(){
address=new Address();
}
}
In such case, there is dependency between the Employee and Address (tight coupling). In the
Inversion of Control scenario, we do this something like this:
class Employee{
Address address;
Employee(Address address){
[Link]=address;
}
}
Thus,
BCS 403 By Surendra Kumar, AP AKGEC
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
• makes the code loosely coupled so easy to maintain
• makes the code easy to test
BCS 403 By Surendra Kumar, AP AKGEC
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.
To understand the DI better, Let's understand the Dependency Lookup (DL)
first:
Dependency Lookup
The Dependency Lookup is an approach where we get the resource after
demand. There can be various ways to get the resource for example:
A obj = new AImpl();
In such way, we get the resource(instance of A class) directly by new keyword.
Another way is factory method:
A obj = [Link]();
This way, we get the resource (instance of A class) by calling the static factory
method getA().
BCS 403 By Surendra Kumar, AP AKGEC
Alternatively, we can get the resource by JNDI (Java Naming Directory
Interface) as:
Context ctx = new InitialContext();
Context environmentCtx = (Context) [Link]("java:comp/env");
A obj = (A)[Link]("A");
There can be various ways to get the resource to obtain the resource.
BCS 403 By Surendra Kumar, AP AKGEC
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:
BCS 403 By Surendra Kumar, AP AKGEC
There are 5 methods that starts from m, 2 methods
class A{ that starts from n and 3 methods that starts from p.
public void m1(){...} • Understanding Scenario I have to maintain log and
send notification after calling methods that starts
public void m2(){...} from m.
public void m3(){...} • Problem without AOP We can call methods (that
public void m4(){...} maintains log and sends notification) from the
methods starting with m. In such scenario, we
public void m5(){...} need to write the code in all the 5 methods.
public void n1(){...} • But, if client says in future, I don't have to send
public void n2(){...} notification, you need to change all the methods. It
public void p1(){...} leads to the maintenance problem.
• Solution with AOP We don't have to call methods
public void p2(){...} from the method. Now we can define the
public void p3(){...} 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.
BCS 403 By Surendra Kumar, AP AKGEC
Where use AOP?
AOP is mostly used in following cases:
• to provide declarative enterprise services such as declarative transaction
management.
• It allows users to implement custom aspects.
• AOP Concepts and Terminology
• AOP concepts and terminologies are as follows:
– Join point
– Advice
– Pointcut
– Introduction
– Target Object
– Aspect
– Interceptor
– AOP Proxy
– Weaving
BCS 403 By Surendra Kumar, AP AKGEC
AOP concepts and terminologies are as follows:
………………………
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:
• Before Advice: it executes before a join point.
• After Returning Advice: it executes after a joint point completes normally.
• After Throwing Advice: it executes if method exits by throwing an
exception.
• After (finally) Advice: it executes after a join point regardless of join point
exit whether normally or exceptional return.
• Around Advice: It executes before and after a join point.
BCS 403 By Surendra Kumar, AP AKGEC
AOP concepts and terminologies are as follows:
………………………
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.
BCS 403 By Surendra Kumar, AP AKGEC
Bean Scopes
• 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.
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
In Spring Framework, bean scopes define the boundaries within which a bean exists,
its context, and how long it lives. Let’s explore the different bean scopes:
• Singleton (Default): A singleton bean has only one shared instance managed by
the Spring IoC container. All requests for beans with the same ID return this single
instance. It’s like a global singleton cache1.
• Prototype: A prototype bean creates a new instance every time it’s requested.
There’s no shared state between instances. Use this for stateful beans or when you
need fresh instances1.
• Request: Scoped to the lifecycle of an HTTP request in a web-aware Spring
ApplicationContext. Each HTTP request gets its own instance of the bean1.
• Session: Scoped to the lifecycle of an HTTP session. Valid only in a web-aware
Spring ApplicationContext1.
• Application: Scoped to the lifecycle of a ServletContext. Also web-aware1.
• Websocket: Scoped to the lifecycle of a WebSocket. Again, web-aware1.
• Remember that Spring’s singleton scope differs from the Gang of Four (GoF)
singleton pattern. In Spring, it’s about managing instances within the IoC
container, not enforcing a single instance per ClassLoader1. If you have any specific
use case, feel free to ask! 😊
BCS 403 By Surendra Kumar, AP AKGEC
• The following are the different scopes provided for a bean:
• 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.
• Prototype: A new instance will be created for a single bean definition
every time a request is made for that bean.
• 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.
• 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.
• 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.
BCS 403 By Surendra Kumar, AP AKGEC
Bean life cycle in Java Spring
• The lifecycle of any object means when & how it is born, how it
behaves throughout its life, and when & how it dies.
• Similarly, the bean life cycle refers to when & how the bean is
instantiated, what action it performs until it lives, and when & how
it is destroyed.
• Bean life cycle is managed by the spring container. When we run
the program then, first of all, the spring container gets started.
• After that, the container creates the instance of a bean as per the
request, and then dependencies are injected.
• And finally, the bean is destroyed when the spring container is
closed.
• Therefore, if we want to execute some code on the bean
instantiation and just after closing the spring container, then we can
write that code inside the custom init() method and
the destroy() method.
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
Ways to implement the life cycle of a
bean
• Spring provides three ways to implement the life cycle of a
bean. In order to understand these three ways, let’s take an
example.
• In this example, we will write and activate init() and
destroy() method for our bean ([Link]) to print
some messages on start and close of the Spring container.
Therefore, the three ways to implement this are:
• 1. By XML: In this approach, in order to avail custom init()
and destroy() methods for a bean we have to register these
two methods inside the Spring XML configuration file while
defining a bean. Therefore, the following steps are
followed:
BCS 403 By Surendra Kumar, AP AKGEC
• 2. By Programmatic Approach: To provide the facility to the
created bean to invoke custom init() method on the startup of a
spring container and to invoke the custom destroy() method on
closing the container,
we need to implement our bean with two interfaces
namely InitializingBean, DisposableBean and will have to
override afterPropertiesSet() and destroy() method.
• afterPropertiesSet() method is invoked as the container starts
and the bean is instantiated whereas, the destroy() method is
invoked just after the container is closed.
Note: To invoke destroy method we have to call a close() method
of ConfigurableApplicationContext.
BCS 403 By Surendra Kumar, AP AKGEC
3. Using Annotation:
• To provide the facility to the created bean to invoke
custom init() method on the startup of a spring container and
• to invoke the custom destroy() method on closing the
container, we need to annotate init() method
by @PostConstruct annotation and destroy() method
by @PreDestroy annotation.
Note: To invoke the destroy() method we have to call
the close() method of ConfigurableApplicationContext.
BCS 403 By Surendra Kumar, AP AKGEC
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 ([Link])
2. Using @Component Annotation
3. Using @Bean Annotation
BCS 403 By Surendra Kumar, AP AKGEC
Method 1: Creating Bean Inside an XML Configuration File
([Link])
• 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.
BCS 403 By Surendra Kumar, AP AKGEC
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 [Link] file. BCS 403 By Surendra Kumar, AP AKGEC
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 [Link] file.
BCS 403 By Surendra Kumar, AP AKGEC
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.
BCS 403 By Surendra Kumar, AP AKGEC
// 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)
{
[Link] = name;
}
// Create a getter method so that
// the user can get the set value
public String getName()
{
return name;
}
}
BCS 403 By Surendra Kumar, AP AKGEC
Step 2: Now, we write a Spring XML configuration
file “[Link]” and configure the bean defined
above.
<!DOCTYPE beans PUBLIC
"-//SPRING//DTD BEAN 2.0//EN"
"[Link]
[Link]">
<beans>
<!--configure the bean [Link]
and declare its scope-->
< bean
id = "hw"
class= "[Link]"
scope = "singleton" / >
</beans>
BCS 403 By Surendra Kumar, AP AKGEC
Step 3: Finally, write a driver class “[Link]” to request the
above bean. public static void main(String[] args)
// Java program to illustrate {
// the client to perform the // Load the Spring XML
// request to the defined bean configuration
// file into IoC container
ApplicationContext
package driver;
ap
= new
import [Link]
ClassPathXmlApplicationContext(
.[Link]; "resources/[Link]");
import [Link] // Get the "HelloWorld" bean
.[Link] object
.ClassPathXmlApplicationContext; // and call getName() method
HelloWorld Geeks1
import [Link]; =
(HelloWorld)[Link]("hw");
// Client Class to request the
// above defined bean // Set the name
public class Client { [Link]("Geeks1");
BCS 403 By Surendra Kumar, AP AKGEC
[Link](
"Hello object (hello1)"
// Get another "HelloWorld" bean object
// and call getName() method
HelloWorld Geeks2
= (HelloWorld)[Link]("hw");
[Link](
"Hello object (hello2)"
+ " Your name is: "
+ [Link]());
// Now compare the references to see
// whether they are pointing to the
// same object or different object
[Link](
BCS 403 By Surendra Kumar, AP AKGEC
"'Geeks1' and 'Geeks2'"
+ " are referring"
+ "to the same object: "
+ (Geeks1 == Geeks2));
// Print the address of both
// object Geeks1 and Geeks2
[Link](
"Address of object Geeks1: "
+ Geeks1);
[Link](
"Address of object Geeks2: "
+ Geeks2);
}
}
BCS 403 By Surendra Kumar, AP AKGEC
• 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.
BCS 403 By Surendra Kumar, AP AKGEC
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:
BCS 403 By Surendra Kumar, AP AKGEC
Step 1: Let us 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)
{
[Link] = name;
}
// Create a getter method so that
// the user can get the set value
public String getName()
{
return name;
}
}
BCS 403 By Surendra Kumar, AP AKGEC
Step 2: Now, we write a Spring XML configuration file
“[Link]” and configure the bean defined above.
<!DOCTYPE beans PUBLIC
"-//SPRING//DTD BEAN 2.0//EN"
"[Link]
[Link]">
< beans>
<!--configure the bean [Link]
and declare its scope-->
< bean
id = "hw"
class = "[Link]"
scope = "prototype" / >
</ beans>
BCS 403 By Surendra Kumar, AP AKGEC
Step 3: Finally, write a
public static void main(String[] args)
driver class “[Link]” {
to request the above // Load the Spring XML
configuration
bean. // file into IoC container
// Java program to illustrate ApplicationContext ap
// the client to perform the = new
// request to the defined bean ClassPathXmlApplicationContext(
"resources/[Link]");
package driver;
// Get the "HelloWorld"
import [Link]
bean object
.[Link]; // and call getName()
method
import [Link] HelloWorld Geeks1
.ClassPathXmlApplicationContext; =
(HelloWorld)[Link]("hw");
import [Link];
// Set the name
public class Client {
[Link]("Geeks1");
BCS 403 By Surendra Kumar, AP AKGEC
[Link](
"Hello object (hello1)"
+ " Your name is: "
+ [Link]());
// Get another "HelloWorld" bean object
// and call getName() method
HelloWorld Geeks2
= (HelloWorld)[Link]("hw");
[Link](
"Hello object (hello2)"
+ "Your name is: "
+ [Link]());
BCS 403 By Surendra Kumar, AP AKGEC
// Now compare the references to see
// whether they are pointing to the
// same object or different object
[Link](
"'Geeks1' and 'Geeks2'"
+ "are referring "
+ "to the same object: "
+ (Geeks1 == Geeks2));
// Print the address of both
// object Geeks1 and Geeks2
[Link](
"Address of object Geeks1: "
+ Geeks1);
[Link](
"Address of object Geeks2: "
+ Geeks2);
}
}
BCS 403 By Surendra Kumar, AP AKGEC
• 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.
BCS 403 By Surendra Kumar, AP AKGEC
Difference between Singleton and
Prototype
Singleton Prototype
A new instance is created for a single
Only one instance is created for a single
bean definition every time a request is
bean definition per Spring IoC container
made for that bean.
Same object is shared for each request For each new request a new instance is
made for that bean. i.e. The same object created. i.e. A new object is created each
is returned each time it is injected. time it is injected.
By default scope of a bean is singleton. So By default scope is not prototype so you
we don’t need to declare a been as have to declare the scope of a been as
singleton explicitly. prototype explicitly.
Singleton scope should be used for While prototype scope is used for all
stateless beans. beans that are stateful
BCS 403 By Surendra Kumar, AP AKGEC
The Request Bean Scope
• The request scope is applicable to beans of
Web aware applications. This scope defines a
single bean definition that lives within a single
HTTP request. This means every HTTP request
will have its own instance of a bean.
• I’ll demonstrate how the Request scope works
through a REST controller.
• The code of the REST controller is this.
BCS 403 By Surendra Kumar, AP AKGEC
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
@RestController
@RequestScope
public class RequestScopeController {
@GetMapping("message")
public String getMessage() {
[Link](this);
return "Hello from RequestScopeController";
}
}
BCS 403 By Surendra Kumar, AP AKGEC
The preceding code creates a REST controller. The
@RequestScope
annotation sets the scope of the controller to Request.
The getMessage()
handler method print out the current controller instance and returns
a String
as the [Link]: The
@RequestScope
annotation is equivalent to @Scope("singleton")
Run the application. Then open a browser to make two requests with
this URL:
[Link]
The output in the IntelliJ Console is this.
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
The Session Bean Scope
The session scope defines a single bean definition which lives within the lifecycle of an HTTP Session.
Similar to the Request scope, the Session scope is applicable to beans in Web applications.
The code for a REST controller with session scope is this.
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@RestController
@SessionScope
public class SessionScopeController {
@GetMapping("/session/message")
public String getMessage() {
[Link](this);
return "Hello from SessionScopeController";
}
}
BCS 403 By Surendra Kumar, AP AKGEC
Run the application and access the controller multiple times from a browser
window using this URL.
[Link]
The application output is this.
BCS 403 By Surendra Kumar, AP AKGEC
• Note the output. As the requests are coming from the same session, the
same controller instance is serving the requests.
• Open a browser window in incognito mode and access the same URL a few
times.
The application output now is this.
• As you can see, because the requests are now being sent from a different
session, a new controller instance serves the current set of requests.
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC
BCS 403 By Surendra Kumar, AP AKGEC