0% found this document useful (0 votes)
11 views43 pages

Ilovepdf Merged

The Spring Framework is an open-source application framework for developing Java applications, known for its lightweight and flexible nature, which enhances coding efficiency and reduces development time. It utilizes dependency injection to promote loose coupling among components, allowing developers to focus on business logic rather than infrastructure. Spring Boot, an extension of the Spring Framework, simplifies the development of standalone applications by providing embedded servers and autoconfiguration, thus streamlining the process of building microservices and web apps.

Uploaded by

satyamsingh26002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views43 pages

Ilovepdf Merged

The Spring Framework is an open-source application framework for developing Java applications, known for its lightweight and flexible nature, which enhances coding efficiency and reduces development time. It utilizes dependency injection to promote loose coupling among components, allowing developers to focus on business logic rather than infrastructure. Spring Boot, an extension of the Spring Framework, simplifies the development of standalone applications by providing embedded servers and autoconfiguration, thus streamlining the process of building microservices and web apps.

Uploaded by

satyamsingh26002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

8/4/23, 3:25 PM What is Spring Framework?

| Definition from TechTarget

The Spring Framework (Spring) is an open-source application framework that provides infrastructure support
for developing Java applications. One of the most popular Java Enterprise Edition (Java EE) frameworks,
Spring helps developers create high performing applications using plain old Java objects (POJOs).

A framework is a large body of predefined code to which developers can add code to solve a problem in a
specific domain. There are many popular Java frameworks including Java Server Faces (JSF), Maven,
Hibernate, Struts, and Spring.

Released in June 2003 by Rod Johnson under the Apache 2.0 license, the Spring Framework is hosted by
SourceForge.

Why Spring?
Java programs are complex and feature many heavyweight components. Heavyweight means the
components are dependent on the underlying operating system (OS) for their appearance and properties.

Spring is considered to be a secure, low-cost and flexible framework. Spring improves coding efficiency and
reduces overall application development time because it is lightweight -- efficient at utilizing system
resources -- and has a lot of support.

Spring removes tedious configuration work so that developers can focus on writing business logic. Spring
handles the infrastructure so developers can focus on the application.

How Spring works


A web application (layered architecture) commonly includes three layers:

1. Presentation/view layer (UI) - This is the outermost layer which handles the presentation of content and
interaction with the user.
2. Business logic layer - The central layer that deals with the logic of a program.
3. Data access layer - The deep layer that deals with data retrieval from sources.

Each layer is dependent on the other for an application to work. In other words, the presentation layer talks to
the business logic layer, which talks to the data access layer. Dependency is what each layer needs to
perform its function. A typical application has thousands of classes and many dependencies.

Without a Spring Framework, application code tends to be tightly coupled (interdependent), which is not
considered good coding practice. Loose coupling is ideal because loosely coupled components are
independent, meaning changes in one will not affect the operation of others.

Spring’s core logic is dependency injection. Dependency injection is a programming pattern that allows
developers to build more decoupled architectures. Dependency injection means that Spring understands the
different Java annotations that a developer puts on top of classes. Spring knows that the developer wants to
https://www.techtarget.com/searchapparchitecture/definition/Spring-Framework 1/2
8/4/23, 3:25 PM What is Spring Framework? | Definition from TechTarget

create an instance of a class and that Spring should manage it. Spring also understands the dependency
and makes sure that all instances created have properly populated dependencies.

For the Spring Framework to instantiate objects and populate the dependencies, a programmer simply tells
Spring which objects to manage and what the dependencies are for each class. A developer does so by
using annotations like:

@component - Lets Spring know which classes to manage (create). Marks the beans (objects) as
managed components, which means that Spring will autodetect these classes for dependency injection.

@autowired - Tells Spring how to handle the instantiation of the class (so it starts looking for that dependency
among components/classes to find a match). This spares developers from wiring with code and allows
Spring to find what needs to be injected where.

Important terms
Autowiring - The process by which Spring identifies dependencies and matches and populates them.

Bean - A Spring bean is an object that is instantiated, created, and managed by the IoC container. Beans are
the backbone of an application.

Dependency injection - A programming design pattern that makes code loosely coupled, meaning that any
change in the application of one, will not affect the other.

Inversion of control (IoC) - Taking control away from the class and giving it to the Spring Framework.

Inversion of control container - This is the core of the Spring Framework where objects are created, wired
together, configured, and managed throughout their life cycle.

https://www.techtarget.com/searchapparchitecture/definition/Spring-Framework 2/2
Azure

 Sign In

What is Java Spring Boot?


An intro to Spring Boot—the popular, Java-based tool for developing web apps and microservices.

 Chat with sales


What is Spring Boot?
Java Spring Boot is an open-source tool that makes it easier to use Java-based frameworks to create microservices and web apps. For any definition
of Spring Boot, the conversation has to start with Java—one of the most popular and widely used development languages and computing platforms
for app development. Developers all over the world start their coding journey learning Java. Flexible and user-friendly, Java is a developer favorite
for a variety of apps—everything from social media, web, and gaming apps to networking and enterprise applications.

Java and the Spring framework

While Java may be easy to use and easier to learn than other languages, the level of complexity to build, debug, and deploy Java apps has escalated
to dizzying new heights. This is due to the exponential number of variables modern developers are faced with when developing web apps or mobile
apps for common modern technologies such as music streaming or mobile cash payment apps. A developer writing a basic line-of-business app now
needs to deal with multiple libraries, plugins, error logging and handling libraries, integrations with web services, and multiple languages such as C#,
Java, HTML, and others. Understandably, there is an insatiable demand for any tools that will streamline Java app development, saving the developers
time and money.

Enter application frameworks—the large bodies of prewritten code that developers can use and add to their own code, as their needs dictate. These
frameworks lighten the developer's load for almost any need—whether they're developing mobile and web apps or working with desktops and APIs.
Frameworks make creating apps quicker, easier, and more secure by providing reusable code and tools to help tie the different elements of a software
development project all together.

Here's where Spring comes in: Spring is an open-source project that provides a streamlined, modular approach for creating apps with Java. The family
of Spring projects began in 2003 as a response to the complexities of early Java development and provides support for developing Java apps. The
name, Spring, alone usually refers to the application framework itself or the entire group of projects, or modules. Java Spring Boot is one specific
module that is built as an extension of the Spring framework.

So, with that background on how the Spring framework, Spring Boot, and Java work together, here's the definition of Spring Boot—the tool that
streamlines and speeds up web app and microservices development within the Java framework, Spring.

Sometimes, because the language and/or platform is Java, it gets referred to as "Java Spring Boot," the "Java Spring framework," or the "Spring Boot
framework." However, because there are other third-party frameworks for Java, such as Play and Hibernate, it's more accurate to say "Spring" and
"Spring Boot."

For a high-level discussion of Java basics, check out the article, What is Java?

What's the difference between Spring and Spring Boot?


As mentioned earlier, Spring is an open-source, Java-based app framework that covers many smaller projects under its umbrella. Other
popular Spring projects include Spring Data, Spring Cloud, and Spring Security, just to name a few. To understand the difference between Spring
Boot vs. Spring, it's important to realize that, even though there may be differences in core capabilities, it's all in the Spring family.

To fully understand the differences between Spring and Spring Boot, we'll need to define a few key terms first.


What are microservices?
Microservices are an approach to software development architecture. The "micro" in microservices refers to code being delivered in small,
manageable pieces, or components, and each "service" or core function, is created and deployed independently from the other services. The
independent components work together and communicate through prescribed API documents called contracts. The small scale and relative isolation
of these microservices has many benefits. For example, because this type of architecture is distributed and loosely coupled, the whole app doesn't
break if one component fails. Other benefits are improved productivity, easier maintenance, better business alignment, and greater fault tolerance.

What is dependency injection?


Dependency injection (DI) is a design technique used to achieve inversion of control (IoC). In object-oriented programming like Java, objects that
depend on other objects are called dependencies. Typically, the receiving or dependent object is called a client and the object that the client is
dependent on is called a service. So, dependency injection passes the service to the client, or "injects" the dependency using code called an injector.
DI eliminates the need for the client to specify which service to use—the injector does that work for the client.


What is convention over configuration?
Convention over configuration, sometimes called coding by convention, is a concept used in application frameworks to reduce the number of
decisions that a developer has to make. It adheres to the "don't repeat yourself" principle to avoid writing redundant code. Coding by convention
strives to maintain flexibility while allowing a developer to only write code for the unconventional aspects of the app they're creating. When the
desired behavior of the app matches the conventions established, the app will just run by default without having to write configuration files. The
developer will only need to explicitly write configuration files if the desired behavior strays from the "convention."


Spring framework vs. Spring Boot
Because Spring Boot is built on the benefits of the Spring framework, it's not really an "either/or" question of Spring vs. Spring Boot, but rather a
"both/and" benefit. It's not Spring vs Spring Boot; Spring and Spring Boot go hand in hand:

Spring Spring Boot

What is it? An open-source web application framework based An extension or module built on the Spring framework.
on Java.

What does it do? Provides a flexible, completely configurable Provides the ability to create, standalone Spring
environment using tools and libraries of prebuilt applications that can just run immediately without the
code to create customized, loosely coupled web need for annotations, XML configuration, or writing lots
apps. of additional code.

When should I use it? Use Spring when you want: Use Spring Boot when you want:

Flexibility. Ease of use.


An unopinionated approach.* An opinionated approach.*
To remove dependencies from your custom To get quality apps running quickly and reduce
code. development time.
To implement a very unique configuration. To avoid writing boilerplate code or configuring
To develop enterprise applications. XML.
To develop REST APIs.

What's its key feature? Dependency injection Autoconfiguration

Does it have embedded No. In Spring, you'll need to set up the servers Yes, Spring Boot comes with built-in HTTP servers like
servers? explicitly. Tomcat and Jetty.

How is it configured? The Spring framework provides flexibility, but its Spring Boot configures Spring and other third-party
configuration has to be built manually. frameworks automatically by the default "convention
over configuration" principle.

Do I need to know how to In Spring, knowledge of XML configuration is Spring Boot does not require XML configuration.
work with XML? required.

Are there CLI tools for The Spring framework alone doesn't provide CLI As a Spring module, Spring Boot has a CLI tool for
dev/testing apps? tools for developing or testing apps. developing and testing Spring-based apps.

Does it work from an Unopinionated* Opinionated*


opinionated or
unopinionated approach?

*Opinionated vs. unopinionated framework approach

While the word "opinionated" may sound vaguely negative, both the opinionated approach of Spring Boot and the unopinionated Spring framework
have their advantages.

Opinionated approach
An opinionated approach takes the position that there is one way that is significantly easier than all the others. By design, the software limits designers,
encouraging them into doing things in that prescribed way.

It provides a well-paved path, a best practice that will work for most people in most situations. The app is written sticking closely to these best practices
and widespread conventions. An opinionated approach makes collaboration and getting help with a coding project much easier—other developers who
have experience with that framework will have immediate familiarity with the new app and can jump right in.

Unopinionated approach
An unopinionated approach is adopted if all solutions require roughly the same amount of effort or complexity. It takes the position that there's no one
right way to arrive at a solution to a problem. Rather, it provides flexible tools that can be used to solve the problem in many ways. Unopinionated
frameworks have the benefit of providing lots of flexibility in development and they put more of the control in developers' hands. The main
disadvantage with so much flexibility is that the developer has more decisions to make and may end up having to write more code because the
framework is so open-ended and well, unopinionated.

Spring Boot features and benefits


Finally, the exciting part—the core capabilities that Java Spring Boot provides beyond the Spring framework. Spring Boot gives an easier, quicker
path to set up, configure, and run apps. It eliminates the heavy lifting of configuration that is required for setting up most Spring-based apps.
Developers can jump right in and use Spring Boot without ever having to learn the underlying Spring framework.


Here's how Spring Boot features help to streamline Java programming tasks. Some key features of Spring Boot are:

 Standalone applications—Spring Boot helps create apps that aren't tied to a specific platform and that can run locally on a device without an
internet connection or other installed services to be functional.

 Embedded servers—Spring Boot allows you to embed servers such as Tomcat, Jetty, or Undertow directly.

 Opinionated approach—Spring Boot simplifies build configurations by providing opinionated starter dependencies.

 Autoconfiguration—Spring Boot automatically configures Spring and other third-party libraries whenever possible.

 Production-ready features—Spring Boot provides production-ready features such as metrics, health checks, and externalized configuration.

Benefits of Spring Boot


Spring Boot:

 Reduces time in development and increases productivity—Spring Boot makes it much easier to develop Spring-based apps with Java. Its
opinionated approach to the Spring framework decreases the time spent on decisions and repetitive tasks and frees up time to focus on creating
and testing the apps.

 Decreases the need to write boilerplate code, annotations, and XML configuration—There's no need for developers to generate code or
configure XML or even learn the Spring framework, if they don't want to.


 Integrates apps in the Spring project family—Spring Boot apps integrate seamlessly with other projects in the Spring framework ecosystem—
such as Spring Data, Spring Cloud, Spring Security—as well as with other trusted cloud services such as Microsoft Azure Spring Cloud.

 Provides dev/test tools—With Spring Boot's command-line interface (CLI) tool and embedded HTTP servers, it makes it very simple to create
environments to dev/test Spring-based apps.

 Offers plugins and tools to make development easier—Spring Boot offers plugins to be able to work with in-memory databases, as well as other
popular build automation tools such as Apache Maven.

Java Spring Boot tutorials


If you're already familiar with building apps using the Spring framework, you'll probably find it straightforward to learn Spring Boot using the
tutorials, project starters, and documentation provided in this section. But here's some good news if you're in a hurry to use Spring Boot but don't
know the framework yet. It's possible to learn Spring Boot —and get started working with it—before learning the Spring framework, because you'll
pick up many of the framework fundamentals as you go along. While this won't teach you everything there is to know about the framework, it will
give you a good head start if you decide to learn it later on.

Another benefit of learning Spring Boot, besides making app development much faster and more efficient, is that it also sets you up to be able to
use other Spring capabilities, namely Spring Data, Project Reactor, and Spring Security.


That said, you'll find it easier to work through your first Spring Boot tutorial if you first learn how the basic concepts of dependency injection and
inversion of control work in the Spring framework. Here's a very high-level overview:

Dependency injection
XML-based, i.e., <beans/> and <namespace:*/>.
Annotation-based, i.e., @Component, @Autowired, @Inject.
Java-based, i.e., @Configuration classes, @Bean methods.

Inversion of control (IoC)


ApplicationContext—the root interface that serves as the Spring IoC container.
BeanFactory—the interface to access the Spring container.
Beans—the objects instantiated, assembled, and managed by ApplicationContext.

Java Spring Boot tutorials for beginners


Once you've mastered the basics, if you're looking to build and deploy Spring Boot apps at scale, consider checking out the fully managed Azure Spring
Cloud service from Microsoft and VMware. Or—get started right away with this tutorial on how to secure your Spring Boot apps with TLS/SSL
certificates.

Create and help secure a Java app Deploy your first app to Azure Spring Cloud
Create a Java app with the Spring Initializr using the Spring Boot Learn to create, provision, and monitor a simple Spring Boot app
starter for Microsoft Entra ID (formerly Azure Active Directory). built with Spring Initializr.

Get started  Get started 

Build a simple Spring Boot microservice More Spring Boot starters


Build and deploy a simple microservice—and then learn to add Add storage, security, authentication, and key vault features to
Spring Cloud technologies to it. your Spring Boot apps.

Get started  Get started 


FAQs Expand all | Collapse all

What is Java Spring Boot?


What is Spring Boot in Java?


 What's the difference between Spring and Spring Boot?

Spring Boot has the functionality of the general Spring framework,


but Spring Boot doesn't require you to learn Spring. A developer
can get an app up and running with less time because Spring Boot
attributes are autoconfigured and the opinionated approach
removes much of the boilerplate code and configuration involved
with Spring app development and deployment.

Learn more 

Is Spring Boot a backend system?


What are the benefits of Spring Boot?


Where can I find Spring Boot tutorials for beginners?


Ready when you are—let's set up your Azure free account

Try Azure for free

Get the Azure mobile app

Explore Azure
Explore Azure

What is Azure?

Get started

Global infrastructure

Datacentre regions

Trust your cloud

Customer enablement

Customer stories
Products and pricing

Products and pricing

Products

Pricing

Free Azure services

Flexible purchase options

Cloud economics

Optimise your costs


Solutions and support
Solutions and support

Solutions

Resources for accelerating growth

Solution architectures

Support

Azure demo and live Q&A


Partners
Partners

Azure Marketplace

Find a partner

Technology partners
Resources
Resources

Training and certifications

Documentation

Blog

Developer resources

Students

Events and webinars

Analyst reports, white papers and e-books

Videos
Cloud computing
Cloud computing

What is cloud computing?

What is cloud migration?

What is a hybrid cloud?

What is AI?

What is IaaS?

What is SaaS?

What is PaaS?

What is DevOps?

Change language

English (India)

Your Privacy Choices

Diversity and Inclusion Accessibility Privacy & Cookies Data Protection Notice Trademarks Terms of use Privacy Data Management Contact us Feedback Sitemap

© Microsoft 2023


8/4/23, 3:35 PM Learn Spring Tutorial - javatpoint

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){
this.address=address;
}
}

Thus, 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

https://www.javatpoint.com/spring-tutorial 1/2
8/4/23, 3:35 PM Learn Spring Tutorial - javatpoint

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.

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

5) Fast Development

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

6) Powerful abstraction

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

7) Declarative support

https://www.javatpoint.com/spring-tutorial 2/2
8/9/23, 3:54 PM Spring Bean Life Cycle and Callbacks - Dinesh on Java

Spring Bean Life Cycle and


Callbacks

In this article, you’ll be given an overview of Spring Bean Life cycle


managed by the spring container, including understanding of Spring
containers and IoC. You’ll also get an overview of the spring bean life cycle
call back handlers and post processors. The Spring Framework provide
several call back methods to created a bean and some method to be destroy
the bean in the Spring IoC Container.

@ImageSource-Youtube

The Spring Framework provides several marker interfaces to change the


behavior of your bean in the container; they
include InitializingBean and DisposableBean. Implementing these interfaces
will result in the container calling afterPropertiesSet() for the former
and destroy() for the latter to allow the bean to perform certain actions upon
initialization and destruction.

Popular Tutorials
Spring Tutorial
Spring MVC Web Tutorial
Spring Boot Tutorial
Spring Security Tutorial
Spring AOP Tutorial
Spring JDBC Tutorial
Spring HATEOAS
https://www.dineshonjava.com/bean-lifecycle-and-callbacks/ 1/11
8/9/23, 3:54 PM Spring Bean Life Cycle and Callbacks - Dinesh on Java

Microservices with Spring Boot


REST Webservice
Core Java
Hibernate Tutorial
Spring Batch

Understanding Spring bean life cycle


The Spring bean life cycle 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 is lists of the activities that take place behind the scenes
between the time of bean Instantiation and its destruction, but this chapter
will discuss only two important bean life cycle callback methods which
are required at the time of bean initialization and its destruction.

Beans can be notified after creation and all properties are set, and before they
are destroyed and removed from the bean container. This involves specifying
the callback method to be invoked by the container. This is done in XML by
specifying attributes init-method=”myinit”, for the initialization callback,
and destroy-method=”mydestroy”, for the destroy callback. “myinit” and
“cleanUp” are names of instance methods in the bean class.

Initialization callbacks
Implementing
the org.springframework.beans.factory.InitializingBean interface allows a
bean to perform initialization work after all necessary properties on the bean
are set by the container. The InitializingBean interface specifies exactly one
method:
org.springframework.beans.factory.InitializingBean interface provide
Initialization callbacks method as given below..

void afterPropertiesSet() throws Exception

Now we can implements above interface and do some initialization


functionality with in this method. As below..

https://www.dineshonjava.com/bean-lifecycle-and-callbacks/ 2/11
8/9/23, 3:54 PM Spring Bean Life Cycle and Callbacks - Dinesh on Java

public class Triangle implements InitializingBean


{
@Override
public void afterPropertiesSet() throws Exception
{
//To do some initialization works here
System.out.println("InitializingBean init method
}
}

Generally, the use of the InitializingBean interface can be avoided (and is


discouraged since it unnecessarily couples the code to Spring). A bean
definition provides support for a generic initialization method to be specified.
In the case of XML-based configuration metadata, this is done using the
‘init-method’ attribute. For example, the following definition:
In the case of XML-based configuration metadata, we can use the init-
method attribute to specify the name of the method that has a void no-
argument signature. For example:

<bean class="com.dineshonjava.sdnext.callbackLifecycle

Now following has myInit method in class.

public class Triangle


{
public void myInit()
{
//To do some initialization works here
System.out.println("My init method is called for T
}
}

Now using Java annotations can also be used to declare bean life cycle
callbacks.

public class Triangle


{

https://www.dineshonjava.com/bean-lifecycle-and-callbacks/ 3/11
8/9/23, 3:54 PM Spring Bean Life Cycle and Callbacks - Dinesh on Java

//init callback
@PostConstruct
public void myInit()
{
//To do some initialization works here
System.out.println("My init method is called for T
}
}

Destruction callbacks
Implementing
the org.springframework.beans.factory.DisposableBean interface allows a
bean to get a callback when the container containing it is destroyed. The
DisposableBean interface specifies one method:

void destroy() throws Exception

Now we can implements above interface and do some Destruction


functionality with in this method. As below..

public class Triangle implements DisposableBean


{
@Override
public void destroy() throws Exception
{
//To do some Destruction works here
System.out.println("DisposableBean destroy metho
}
}

Generally, the use of the DisposableBean marker interface can be avoided


(and is discouraged since it unnecessarily couples the code to Spring). A bean
definition provides support for a generic destroy method to be specified.
When using XML-based configuration metadata this is done via the ‘destroy-
method’ attribute on the . For example, the following definition:
In the case of XML-based configuration metadata, we can use the destroy-
method attribute to specify the name of the method that has a void no-
argument signature. For example:

https://www.dineshonjava.com/bean-lifecycle-and-callbacks/ 4/11
8/9/23, 3:54 PM Spring Bean Life Cycle and Callbacks - Dinesh on Java

<bean class="com.dineshonjava.sdnext.callbackLifecycle

Now following has cleanUp method in class.

public class Triangle


{
public void cleanUp()
{
//To do some Destruction works here
System.out.println("cleanUp method is called for T
}
}

Now using Java annotations can also be used to declare bean life cycle
callbacks.

public class Triangle


{
//destroy callback
@PreDestroy
public void myInit()
{
//To do some Destruction works here
System.out.println("cleanUp method is called for T
}
}

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.
Lets see the Example:
Triangle.java

https://www.dineshonjava.com/bean-lifecycle-and-callbacks/ 5/11
8/9/23, 3:54 PM Spring Bean Life Cycle and Callbacks - Dinesh on Java

package com.dineshonjava.sdnext.callbackLifecycle.tutor

import org.springframework.beans.factory.DisposableBean
import org.springframework.beans.factory.InitializingBe

public class Triangle implements InitializingBean, Disp


{
private Point pointA;
private Point pointB;
private Point pointC;
/**
* @param pointA the pointA to set
*/
public void setPointA(Point pointA) {
this.pointA = pointA;
}

/**
* @param pointB the pointB to set
*/
public void setPointB(Point pointB) {
this.pointB = pointB;
}

/**
* @param pointC the pointC to set
*/
public void setPointC(Point pointC) {
this.pointC = pointC;
}

public void draw()


{
System.out.println("PointA is ("+pointA.getX()+", "+poi
System.out.println("PointB is ("+pointB.getX()+", "+poi
System.out.println("PointC is ("+pointC.getX()+", "+poi
}

@Override
public void afterPropertiesSet() throws Exception
{
System.out.println("InitializingBean init method is cal
}

@Override
public void destroy() throws Exception
{
System.out.println("DisposableBean destroy method is ca
}

public void myInit()


https://www.dineshonjava.com/bean-lifecycle-and-callbacks/ 6/11
8/9/23, 3:54 PM Spring Bean Life Cycle and Callbacks - Dinesh on Java

{
System.out.println("My init method is called for Tri
}

public void cleanUp()


{
System.out.println("cleanUp method is called for Tri
}
}

Point.java

package com.dineshonjava.sdnext.callbackLifecycle.tutor

public class Point


{
private int x;
private int y;
/**
* @return the x
*/
public int getX() {
return x;
}
/**
* @param x the x to set
*/
public void setX(int x) {
this.x = x;
}
/**
* @return the y
*/
public int getY() {
return y;
}
/**
* @param y the y to set
*/
public void setY(int y) {
this.y = y;
}
}

Following is the configuration file Spring.xml required


for init and destroy methods.
Spring.xml

https://www.dineshonjava.com/bean-lifecycle-and-callbacks/ 7/11
8/9/23, 3:54 PM Spring Bean Life Cycle and Callbacks - Dinesh on Java

<beans xmlns:aop="http://www.springframework.org/schema

<bean autowire="byName" class="com.dineshonjava.sdnext


</bean>

<bean class="com.dineshonjava.sdnext.callbackLifecycle
<property name="x" value="0"></property>
<property name="y" value="0"></property>
</bean>

<bean class="com.dineshonjava.sdnext.callbackLifecycle
<property name="x" value="-20"></property>
<property name="y" value="0"></property>
</bean>

<bean class="com.dineshonjava.sdnext.callbackLifecycle
<property name="x" value="20"></property>
<property name="y" value="0"></property>
</bean>
</beans>

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

package com.dineshonjava.sdnext.callbackLifecycle.tutor

import org.springframework.context.support.AbstractAppl
import org.springframework.context.support.ClassPathXml

/**
* @author Dinesh Rajput
*
*/
public class DrawingApp
{
/**
* @param args
*/
public static void main(String[] args)
{
AbstractApplicationContext context = new ClassPathXmlAp
context.registerShutdownHook();
Triangle triangle = (Triangle) context.getBean("triangl
triangle.draw();
}

https://www.dineshonjava.com/bean-lifecycle-and-callbacks/ 8/11
8/9/23, 3:54 PM Spring Bean Life Cycle and Callbacks - Dinesh on Java

Output:
Jul 1, 2012 2:48:33 PM
org.springframework.context.support.AbstractApplicationContext
prepareRefresh
INFO: Refreshing
org.springframework.context.support.ClassPathXmlApplicationContext@ab50cd:
startup date [Sun Jul 01 14:48:33 IST 2012]; root of context hierarchy
Jul 1, 2012 2:48:33 PM
org.springframework.beans.factory.xml.XmlBeanDefinitionReader
loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Jul 1, 2012 2:48:33 PM
org.springframework.beans.factory.support.DefaultListableBeanFactory
preInstantiateSingletons
INFO: Pre-instantiating singletons in
org.springframework.beans.factory.support.DefaultListableBeanFactory@1543c88:
defining beans [triangle,pointA,pointB,pointC]; root of factory hierarchy
InitializingBean init method is called for Triangle
My init method is called for Triangle
PointA is (0, 0)
PointB is (-20, 0)
PointC is (20, 0)

Jul 1, 2012 2:48:33 PM


org.springframework.context.support.AbstractApplicationContext doClose
INFO: Closing
org.springframework.context.support.ClassPathXmlApplicationContext@ab50cd:
startup date [Sun Jul 01 14:48:33 IST 2012]; root of context hierarchy
DisposableBean destroy method is called for Triangle
cleanUp method is called for Triangle

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 framework provides the flexibility to configure
https://www.dineshonjava.com/bean-lifecycle-and-callbacks/ 9/11
8/9/23, 3:54 PM Spring Bean Life Cycle and Callbacks - Dinesh on Java

such situation using default-init-method and default-destroy-method


attributes on the <beans> element as follows:
spring.xml

<beans default-destroy-method="cleanUp" default-init-me

<bean autowire="byName" class="com.dineshonjava.sdnext


</bean>

<bean class="com.dineshonjava.sdnext.callbackLifecycle
<property name="x" value="0"></property>
<property name="y" value="0"></property>
</bean>
<bean class="com.dineshonjava.sdnext.callbackLifecycle
<property name="x" value="-20"></property>
<property name="y" value="0"></property>
</bean>
<bean class="com.dineshonjava.sdnext.callbackLifecycle
<property name="x" value="20"></property>
<property name="y" value="0"></property>
</bean>
</beans>

Now again run the application with above the configuration file we will get
the following output:
Output:
Jul 1, 2012 2:58:00 PM
org.springframework.context.support.AbstractApplicationContext
prepareRefresh
INFO: Refreshing
org.springframework.context.support.ClassPathXmlApplicationContext@ab50cd:
startup date [Sun Jul 01 14:58:00 IST 2012]; root of context hierarchy
Jul 1, 2012 2:58:00 PM
org.springframework.beans.factory.xml.XmlBeanDefinitionReader
loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Jul 1, 2012 2:58:01 PM
org.springframework.beans.factory.support.DefaultListableBeanFactory
preInstantiateSingletons
INFO: Pre-instantiating singletons in
org.springframework.beans.factory.support.DefaultListableBeanFactory@1543c88:
defining beans [triangle,pointA,pointB,pointC]; root of factory hierarchy

https://www.dineshonjava.com/bean-lifecycle-and-callbacks/ 10/11
8/9/23, 3:54 PM Spring Bean Life Cycle and Callbacks - Dinesh on Java

InitializingBean init method is called for Triangle


My init method is called for Triangle
PointA is (0, 0)
PointB is (-20, 0)
PointC is (20, 0)
DisposableBean destroy method is called for Triangle
cleanUp method is called for Triangle

https://www.dineshonjava.com/bean-lifecycle-and-callbacks/ 11/11
8/9/23, 10:56 AM 4.4 Bean scopes

4.4 Bean scopes


Prev 4. The IoC container Next

4.4 Bean scopes


When you create a bean definition what you are actually creating is a recipe for creating actual
instances of the class defined by that bean definition. The idea that a bean definition is a recipe is
important, because it means that, just like a class, you can potentially have many object instances
created from a single recipe.

You can control not only the various dependencies and configuration values that are to be plugged into
an object that is created from a particular bean definition, but also the scope of the objects created from
a particular bean definition. This approach is very powerful and gives you the flexibility to choose the
scope of the objects you create through configuration instead of having to 'bake in' the scope of an
object at the Java class level. Beans can be defined to be deployed in one of a number of scopes: out of
the box, the Spring Framework supports exactly five scopes (of which three are available only if you are
using a web-aware ApplicationContext).

The scopes supported out of the box are listed below:

Table 4.4. Bean scopes

Scope Description
Scopes a single bean definition to a single object instance per Spring IoC
singleton
container.
prototype Scopes a single bean definition to any number of object instances.
Scopes a single bean definition to the lifecycle of a single HTTP request; that is
each and every HTTP request will have its own instance of a bean created off the
request
back of a single bean definition. Only valid in the context of a web-aware Spring
ApplicationContext.
Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the
session
context of a web-aware Spring ApplicationContext.
Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically
global
only valid when used in a portlet context. Only valid in the context of a web-aware
session
Spring ApplicationContext.

4.4.1 The singleton scope


When a bean is a singleton, only one shared instance of the bean will be managed, and all requests for
beans with an id or ids matching that bean definition will result in that one specific bean instance being
returned by the Spring container.

To put it another way, when you define a bean definition and it is scoped as a singleton, then the Spring
IoC container will create exactly one instance of the object defined by that bean definition. This single
instance will be stored in a cache of such singleton beans, and all subsequent requests and references
for that named bean will result in the cached object being returned.

https://docs.spring.io/spring-framework/docs/3.0.0.M3/reference/html/ch04s04.html#beans-factory-scopes-singleton 1/9
8/9/23, 10:56 AM 4.4 Bean scopes

Please be aware that Spring's concept of a singleton bean is quite different from the Singleton pattern
as defined in the seminal Gang of Four (GoF) patterns book. The GoF Singleton hard codes the scope
of an object such that one and only one instance of a particular class will ever be created per
ClassLoader. The scope of the Spring singleton is best described as per container and per bean. This
means that if you define one bean for a particular class in a single Spring container, then the Spring
container will create one and only one instance of the class defined by that bean definition. The
singleton scope is the default scope in Spring. To define a bean as a singleton in XML, you would write
configuration like so:

<bean id="accountService" class="com.foo.DefaultAccountService"/>

<!-- the following is equivalent, though redundant (singleton scope is the default); using spring-beans-2.0.dtd -
<bean id="accountService" class="com.foo.DefaultAccountService" scope="singleton"/>

<!-- the following is equivalent and preserved for backward compatibility in spring-beans.dtd -->
<bean id="accountService" class="com.foo.DefaultAccountService" singleton="true"/>

4.4.2 The prototype scope


The non-singleton, prototype scope of bean deployment results in the creation of a new bean instance
every time a request for that specific bean is made (that is, it is injected into another bean or it is
requested via a programmatic getBean() method call on the container). As a rule of thumb, you should
use the prototype scope for all beans that are stateful, while the singleton scope should be used for
stateless beans.

The following diagram illustrates the Spring prototype scope. Please note that a DAO would not typically
be configured as a prototype, since a typical DAO would not hold any conversational state; it was just
easier for this author to reuse the core of the singleton diagram.

https://docs.spring.io/spring-framework/docs/3.0.0.M3/reference/html/ch04s04.html#beans-factory-scopes-singleton 2/9
8/9/23, 10:56 AM 4.4 Bean scopes

To define a bean as a prototype in XML, you would write configuration like so:

<!-- using spring-beans-2.0.dtd -->


<bean id="accountService" class="com.foo.DefaultAccountService" scope="prototype"/>
<!-- the following is equivalent and preserved for backward compatibility in spring-beans.dtd -->
<bean id="accountService" class="com.foo.DefaultAccountService" singleton="false"/>

There is one quite important thing to be aware of when deploying a bean in the prototype scope, in that
the lifecycle of the bean changes slightly. Spring does not manage the complete lifecycle of a prototype
bean: the container instantiates, configures, decorates and otherwise assembles a prototype object,
hands it to the client and then has no further knowledge of that prototype instance. This means that
while initialization lifecycle callback methods will be called on all objects regardless of scope, in the case
of prototypes, any configured destruction lifecycle callbacks will not be called. It is the responsibility of
the client code to clean up prototype scoped objects and release any expensive resources that the
prototype bean(s) are holding onto. (One possible way to get the Spring container to release resources
used by prototype-scoped beans is through the use of a custom bean post-processor which would hold
a reference to the beans that need to be cleaned up.)

In some respects, you can think of the Spring containers role when talking about a prototype-scoped
bean as somewhat of a replacement for the Java 'new' operator. All lifecycle aspects past that point
have to be handled by the client. (The lifecycle of a bean in the Spring container is further described in
the section entitled Section 4.5.1, “Lifecycle callbacks”.)

4.4.3 Singleton beans with prototype-bean dependencies

When using singleton-scoped beans that have dependencies on beans that are scoped as prototypes,
please be aware that dependencies are resolved at instantiation time. This means that if you
dependency inject a prototype-scoped bean into a singleton-scoped bean, a brand new prototype bean
will be instantiated and then dependency injected into the singleton bean... but that is all. That exact
same prototype instance will be the sole instance that is ever supplied to the singleton-scoped bean,
which is fine if that is what you want.

However, sometimes what you actually want is for the singleton-scoped bean to be able to acquire a
brand new instance of the prototype-scoped bean again and again and again at runtime. In that case it
is no use just dependency injecting a prototype-scoped bean into your singleton bean, because as
explained above, that only happens once when the Spring container is instantiating the singleton bean
and resolving and injecting its dependencies. If you are in the scenario where you need to get a brand
new instance of a (prototype) bean again and again and again at runtime, you are referred to the section
entitled Section 4.3.7, “Method Injection”

https://docs.spring.io/spring-framework/docs/3.0.0.M3/reference/html/ch04s04.html#beans-factory-scopes-singleton 3/9
8/9/23, 10:56 AM 4.4 Bean scopes

Backwards compatibility note: specifying the lifecycle scope in XML


If you are referencing the 'spring-beans.dtd' DTD in a bean definition file(s), and you
are being explicit about the lifecycle scope of your beans you must use the
"singleton" attribute to express the lifecycle scope (remembering that the singleton
lifecycle scope is the default). If you are referencing the 'spring-beans-2.0.dtd' DTD
or the Spring 2.0 XSD schema, then you will need to use the "scope" attribute
(because the "singleton" attribute was removed from the definition of the new DTD
and XSD files in favor of the "scope" attribute).

To be totally clear about this, this means that if you use the "singleton" attribute in an
XML bean definition then you must be referencing the 'spring-beans.dtd' DTD in that
file. If you are using the "scope" attribute then you must be referencing either the
'spring-beans-2.0.dtd' DTD or the 'spring-beans-2.5.xsd' XSD in that file.

4.4.4 The other scopes


The other scopes, namely request, session, and global session are for use only in web-based
applications (and can be used irrespective of which particular web application framework you are using,
if indeed any). In the interest of keeping related concepts together in one place in the reference
documentation, these scopes are described here.

Note
The scopes that are described in the following paragraphs are only available if you
are using a web-aware Spring ApplicationContext implementation (such as
XmlWebApplicationContext). If you try using these next scopes with regular Spring IoC
containers such as the XmlBeanFactory or ClassPathXmlApplicationContext, you will get
an IllegalStateException complaining about an unknown bean scope.

4.4.4.1 Initial web configuration

In order to support the scoping of beans at the request, session, and global session levels (web-scoped
beans), some minor initial configuration is required before you can set about defining your bean
definitions. Please note that this extra setup is not required if you just want to use the 'standard' scopes
(namely singleton and prototype).

Now as things stand, there are a couple of ways to effect this initial setup depending on your particular
Servlet environment...

If you are accessing scoped beans within Spring Web MVC, i.e. within a request that is processed by
the Spring DispatcherServlet, or DispatcherPortlet, then no special setup is necessary: DispatcherServlet
and DispatcherPortlet already expose all relevant state.

When using a Servlet 2.4+ web container, with requests processed outside of Spring's
DispatcherServlet (e.g. when using JSF or Struts), you need to add the following
javax.servlet.ServletRequestListener to the declarations in your web application's 'web.xml' file.

<web-app>
...
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
...
</web-app>

If you are using an older web container (Servlet 2.3), you will need to use the provided
javax.servlet.Filter implementation. Find below a snippet of XML configuration that has to be included
in the 'web.xml' file of your web application if you want to have access to web-scoped beans in requests
outside of Spring's DispatcherServlet on a Servlet 2.3 container. (The filter mapping depends on the
surrounding web application configuration and so you will have to change it as appropriate.)

<web-app>
..
<filter>
<filter-name>requestContextFilter</filter-name>
<filter-class>org.springframework.web.filter.RequestContextFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>requestContextFilter</filter-name>
<url-pattern>/*</url-pattern>

https://docs.spring.io/spring-framework/docs/3.0.0.M3/reference/html/ch04s04.html#beans-factory-scopes-singleton 4/9
8/9/23, 10:56 AM 4.4 Bean scopes
</filter-mapping>
...
</web-app>

That's it. DispatcherServlet, RequestContextListener and RequestContextFilter all do exactly the same
thing, namely bind the HTTP request object to the Thread that is servicing that request. This makes
beans that are request- and session-scoped available further down the call chain.

4.4.4.2 The request scope

Consider the following bean definition:

<bean id="loginAction" class="com.foo.LoginAction" scope="request"/>

With the above bean definition in place, the Spring container will create a brand new instance of the
LoginAction bean using the 'loginAction' bean definition for each and every HTTP request. That is, the
'loginAction' bean will be effectively scoped at the HTTP request level. You can change or dirty the
internal state of the instance that is created as much as you want, safe in the knowledge that other
requests that are also using instances created off the back of the same 'loginAction' bean definition will
not be seeing these changes in state since they are particular to an individual request. When the
request is finished processing, the bean that is scoped to the request will be discarded.

4.4.4.3 The session scope

Consider the following bean definition:

<bean id="userPreferences" class="com.foo.UserPreferences" scope="session"/>

With the above bean definition in place, the Spring container will create a brand new instance of the
UserPreferences bean using the 'userPreferences' bean definition for the lifetime of a single HTTP
Session. In other words, the 'userPreferences' bean will be effectively scoped at the HTTP Session level.
Just like request-scoped beans, you can change the internal state of the instance that is created as much
as you want, safe in the knowledge that other HTTP Session instances that are also using instances
created off the back of the same 'userPreferences' bean definition will not be seeing these changes in
state since they are particular to an individual HTTP Session. When the HTTP Session is eventually
discarded, the bean that is scoped to that particular HTTP Session will also be discarded.

4.4.4.4 The global session scope

Consider the following bean definition:

<bean id="userPreferences" class="com.foo.UserPreferences" scope="globalSession"/>

The global session scope is similar to the standard HTTP Session scope (described immediately above),
and really only makes sense in the context of portlet-based web applications. The portlet specification
defines the notion of a global Session that is shared amongst all of the various portlets that make up a
single portlet web application. Beans defined at the global session scope are scoped (or bound) to the
lifetime of the global portlet Session.

Please note that if you are writing a standard Servlet-based web application and you define one or more
beans as having global session scope, the standard HTTP Session scope will be used, and no error will
be raised.

4.4.4.5 Scoped beans as dependencies

Being able to define a bean scoped to a HTTP request or Session (or indeed a custom scope of your
own devising) is all very well, but one of the main value-adds of the Spring IoC container is that it
manages not only the instantiation of your objects (beans), but also the wiring up of collaborators (or
dependencies). If you want to inject a (for example) HTTP request scoped bean into another bean, you
will need to inject an AOP proxy in place of the scoped bean. That is, you need to inject a proxy object
that exposes the same public interface as the scoped object, but that is smart enough to be able to
retrieve the real, target object from the relevant scope (for example a HTTP request) and delegate
method calls onto the real object.

https://docs.spring.io/spring-framework/docs/3.0.0.M3/reference/html/ch04s04.html#beans-factory-scopes-singleton 5/9
8/9/23, 10:56 AM 4.4 Bean scopes

Note
You do not need to use the <aop:scoped-proxy/> in conjunction with beans that are
scoped as singletons or prototypes. It is an error to try to create a scoped proxy for a
singleton bean (and the resulting BeanCreationException will certainly set you straight
in this regard).

Let's look at the configuration that is required to effect this; the configuration is not hugely complex (it
takes just one line), but it is important to understand the “why” as well as the “how” behind it.

<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- a HTTP Session-scoped bean exposed as a proxy -->
<bean id="userPreferences" class="com.foo.UserPreferences" scope="session">
<!-- this next element effects the proxying of the surrounding bean -->
<aop:scoped-proxy/>
</bean>

<!-- a singleton-scoped bean injected with a proxy to the above bean -->
<bean id="userService" class="com.foo.SimpleUserService">

<!-- a reference to the proxied 'userPreferences' bean -->


<property name="userPreferences" ref="userPreferences"/>

</bean>
</beans>

To create such a proxy, you need only to insert a child <aop:scoped-proxy/> element into a scoped bean
definition (you may also need the CGLIB library on your classpath so that the container can effect class-
based proxying; you will also need to be using Appendix A, XML Schema-based configuration). So, just
why do you need this <aop:scoped-proxy/> element in the definition of beans scoped at the request,
session, globalSession and 'insert your custom scope here' level? The reason is best explained by
picking apart the following bean definition (please note that the following 'userPreferences' bean
definition as it stands is incomplete):

<bean id="userPreferences" class="com.foo.UserPreferences" scope="session"/>

<bean id="userManager" class="com.foo.UserManager">


<property name="userPreferences" ref="userPreferences"/>
</bean>

From the above configuration it is evident that the singleton bean 'userManager' is being injected with a
reference to the HTTP Session-scoped bean 'userPreferences'. The salient point here is that the
'userManager' bean is a singleton... it will be instantiated exactly once per container, and its
dependencies (in this case only one, the 'userPreferences' bean) will also only be injected (once!). This
means that the 'userManager' will (conceptually) only ever operate on the exact same 'userPreferences'
object, that is the one that it was originally injected with. This is not what you want when you inject a
HTTP Session-scoped bean as a dependency into a collaborating object (typically). Rather, what we do
want is a single 'userManager' object, and then, for the lifetime of a HTTP Session, we want to see and
use a 'userPreferences' object that is specific to said HTTP Session.

Rather what you need then is to inject some sort of object that exposes the exact same public interface
as the UserPreferences class (ideally an object that is a UserPreferences instance) and that is smart
enough to be able to go off and fetch the real UserPreferences object from whatever underlying scoping
mechanism we have chosen (HTTP request, Session, etc.). We can then safely inject this proxy object
into the 'userManager' bean, which will be blissfully unaware that the UserPreferences reference that it is
holding onto is a proxy. In the case of this example, when a UserManager instance invokes a method on
the dependency-injected UserPreferences object, it is really invoking a method on the proxy... the proxy
will then go off and fetch the real UserPreferences object from (in this case) the HTTP Session, and
delegate the method invocation onto the retrieved real UserPreferences object.

That is why you need the following, correct and complete, configuration when injecting request-,
session-, and globalSession-scoped beans into collaborating objects:

<bean id="userPreferences" class="com.foo.UserPreferences" scope="session">


<aop:scoped-proxy/>

https://docs.spring.io/spring-framework/docs/3.0.0.M3/reference/html/ch04s04.html#beans-factory-scopes-singleton 6/9
8/9/23, 10:56 AM 4.4 Bean scopes
</bean>

<bean id="userManager" class="com.foo.UserManager">


<property name="userPreferences" ref="userPreferences"/>
</bean>

Choosing the type of proxy created

By default, when the Spring container is creating a proxy for a bean that is marked up with the
<aop:scoped-proxy/> element, a CGLIB-based class proxy will be created. This means that you need to
have the CGLIB library on the classpath of your application.

Note: CGLIB proxies will only intercept public method calls! Do not call non-public methods on such a
proxy; they will not be delegated to the scoped target object.

You can choose to have the Spring container create 'standard' JDK interface-based proxies for such
scoped beans by specifying 'false' for the value of the 'proxy-target-class' attribute of the <aop:scoped-
proxy/> element. Using JDK interface-based proxies does mean that you don't need any additional
libraries on your application's classpath to effect such proxying, but it does mean that the class of the
scoped bean must implement at least one interface, and all of the collaborators into which the scoped
bean is injected must be referencing the bean via one of its interfaces.

<!-- DefaultUserPreferences implements the UserPreferences interface -->


<bean id="userPreferences" class="com.foo.DefaultUserPreferences" scope="session">
<aop:scoped-proxy proxy-target-class="false"/>
</bean>
<bean id="userManager" class="com.foo.UserManager">
<property name="userPreferences" ref="userPreferences"/>
</bean>

The section entitled Section 8.6, “Proxying mechanisms” may also be of some interest with regard to
understanding the nuances of choosing whether class-based or interface-based proxying is right for
you.

4.4.5 Custom scopes

As of Spring 2.0, the bean scoping mechanism in Spring is extensible. This means that you are not
limited to just the bean scopes that Spring provides out of the box; you can define your own scopes, or
even redefine the existing scopes (although that last one would probably be considered bad practice -
please note that you cannot override the built-in singleton and prototype scopes).

4.4.5.1 Creating your own custom scope

Scopes are defined by the org.springframework.beans.factory.config.Scope interface. This is the interface


that you will need to implement in order to integrate your own custom scope(s) into the Spring container,
and is described in detail below. You may wish to look at the Scope implementations that are supplied
with the Spring Framework itself for an idea of how to go about implementing your own. The Scope
Javadoc explains the main class to implement when you need your own scope in more detail too.

The Scope interface has four methods dealing with getting objects from the scope, removing them from
the scope and allowing them to be 'destroyed' if needed.

The first method should return the object from the underlying scope. The session scope implementation
for example will return the session-scoped bean (and if it does not exist, return a new instance of the
bean, after having bound it to the session for future reference).

Object get(String name, ObjectFactory objectFactory)

The second method should remove the object from the underlying scope. The session scope
implementation for example, removes the session-scoped bean from the underlying session. The object
should be returned (you are allowed to return null if the object with the specified name wasn't found)

Object remove(String name)

The third method is used to register callbacks the scope should execute when it is destroyed or when
the specified object in the scope is destroyed. Please refer to the Javadoc or a Spring scope

https://docs.spring.io/spring-framework/docs/3.0.0.M3/reference/html/ch04s04.html#beans-factory-scopes-singleton 7/9
8/9/23, 10:56 AM 4.4 Bean scopes
implementation for more information on destruction callbacks.

void registerDestructionCallback(String name, Runnable destructionCallback)

The last method deals with obtaining the conversation identifier for the underlying scope. This identifier
is different for each scope. For a session for example, this can be the session identifier.

String getConversationId()

4.4.5.2 Using a custom scope

After you have written and tested one or more custom Scope implementations, you then need to make
the Spring container aware of your new scope(s). The central method to register a new Scope with the
Spring container is declared on the ConfigurableBeanFactory interface (implemented by most of the
concrete BeanFactory implementations that ship with Spring); this central method is displayed below:

void registerScope(String scopeName, Scope scope);

The first argument to the registerScope(..) method is the unique name associated with a scope;
examples of such names in the Spring container itself are 'singleton' and 'prototype'. The second
argument to the registerScope(..) method is an actual instance of the custom Scope implementation that
you wish to register and use.

Let's assume that you have written your own custom Scope implementation, and you have registered it
like so:

// note: the ThreadScope class does not ship with the Spring Framework
Scope customScope = new ThreadScope();
beanFactory.registerScope("thread", customScope);

You can then create bean definitions that adhere to the scoping rules of your custom Scope like so:

<bean id="..." class="..." scope="thread"/>

If you have your own custom Scope implementation(s), you are not just limited to only programmatic
registration of the custom scope(s). You can also do the Scope registration declaratively, using the
CustomScopeConfigurer class.

The declarative registration of custom Scope implementations using the CustomScopeConfigurer class is
shown below:

<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
<property name="scopes">
<map>
<entry key="thread">
<bean class="com.foo.ThreadScope"/>
</entry>
</map>
</property>
</bean>

<bean id="bar" class="x.y.Bar" scope="thread">


<property name="name" value="Rick"/>
<aop:scoped-proxy/>
</bean>
<bean id="foo" class="x.y.Foo">
<property name="bar" ref="bar"/>
</bean>

</beans>

https://docs.spring.io/spring-framework/docs/3.0.0.M3/reference/html/ch04s04.html#beans-factory-scopes-singleton 8/9
8/9/23, 10:56 AM 4.4 Bean scopes

Note
Note that, when placing a <aop:scoped-proxy/> in a FactoryBean implementation, it is
the factory bean itself that is scoped, not the object returned from getObject().

Prev Up Next
4.3 Dependencies Home 4.5 Customizing the nature of a bean

https://docs.spring.io/spring-framework/docs/3.0.0.M3/reference/html/ch04s04.html#beans-factory-scopes-singleton 9/9
06/12/2023, 15:55 Bean Scopes :: Spring Framework

Bean Scopes
When you create a bean definition, you create a recipe for creating actual instances of the class defined by
that bean definition. The idea that a bean definition is a recipe is important, because it means that, as with a
class, you can create many object instances from a single recipe.

You can control not only the various dependencies and configuration values that are to be plugged into an
object that is created from a particular bean definition but also control the scope of the objects created from a
particular bean definition. This approach is powerful and flexible, because you can choose the scope of the
objects you create through configuration instead of having to bake in the scope of an object at the Java class
level. Beans can be defined to be deployed in one of a number of scopes. The Spring Framework supports six
scopes, four of which are available only if you use a web-aware ApplicationContext . You can also create a
custom scope.

The following table describes the supported scopes:

Table 1. Bean scopes


Scope Description

singleton (Default) Scopes a single bean definition to a single object instance for each Sprin
g IoC container.

prototype Scopes a single bean definition to any number of object instances.

request Scopes a single bean definition to the lifecycle of a single HTTP request. That is, e
ach HTTP request has its own instance of a bean created off the back of a single b
ean definition. Only valid in the context of a web-aware Spring ApplicationContext .

session Scopes a single bean definition to the lifecycle of an HTTP Session . Only valid in t
he context of a web-aware Spring ApplicationContext .

application Scopes a single bean definition to the lifecycle of a ServletContext . Only valid in th
e context of a web-aware Spring ApplicationContext .

websocket Scopes a single bean definition to the lifecycle of a WebSocket . Only valid in the c
ontext of a web-aware Spring ApplicationContext .

A thread scope is available but is not registered by default. For more information, see the
documentation for SimpleThreadScope . For instructions on how to register this or any other custom
scope, see Using a Custom Scope.

The Singleton Scope


Only one shared instance of a singleton bean is managed, and all requests for beans with an ID or IDs that
match that bean definition result in that one specific bean instance being returned by the Spring container.

To put it another way, when you define a bean definition and it is scoped as a singleton, the Spring IoC
container creates exactly one instance of the object defined by that bean definition. This single instance is
stored in a cache of such singleton beans, and all subsequent requests and references for that named bean
return the cached object. The following image shows how the singleton scope works:

https://docs.spring.io/spring-framework/reference/core/beans/factory-scopes.html 1/8
06/12/2023, 15:55 Bean Scopes :: Spring Framework

Spring’s concept of a singleton bean differs from the singleton pattern as defined in the Gang of Four (GoF)
patterns book. The GoF singleton hard-codes the scope of an object such that one and only one instance of a
particular class is created per ClassLoader. The scope of the Spring singleton is best described as being per-
container and per-bean. This means that, if you define one bean for a particular class in a single Spring
container, the Spring container creates one and only one instance of the class defined by that bean definition.
The singleton scope is the default scope in Spring. To define a bean as a singleton in XML, you can define a
bean as shown in the following example:

<bean id="accountService" class="com.something.DefaultAccountService"/>

<!-- the following is equivalent, though redundant (singleton scope is the default) -->
<bean id="accountService" class="com.something.DefaultAccountService" scope="singleton"/>

The Prototype Scope


The non-singleton prototype scope of bean deployment results in the creation of a new bean instance every
time a request for that specific bean is made. That is, the bean is injected into another bean or you request it
through a getBean() method call on the container. As a rule, you should use the prototype scope for all
stateful beans and the singleton scope for stateless beans.

The following diagram illustrates the Spring prototype scope:

https://docs.spring.io/spring-framework/reference/core/beans/factory-scopes.html 2/8
06/12/2023, 15:55 Bean Scopes :: Spring Framework

(A data access object (DAO) is not typically configured as a prototype, because a typical DAO does not hold
any conversational state. It was easier for us to reuse the core of the singleton diagram.)

The following example defines a bean as a prototype in XML:

<bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>

In contrast to the other scopes, Spring does not manage the complete lifecycle of a prototype bean. The
container instantiates, configures, and otherwise assembles a prototype object and hands it to the client, with
no further record of that prototype instance. Thus, although initialization lifecycle callback methods are called
on all objects regardless of scope, in the case of prototypes, configured destruction lifecycle callbacks are not
called. The client code must clean up prototype-scoped objects and release expensive resources that the
prototype beans hold. To get the Spring container to release resources held by prototype-scoped beans, try
using a custom bean post-processor which holds a reference to beans that need to be cleaned up.

In some respects, the Spring container’s role in regard to a prototype-scoped bean is a replacement for the
Java new operator. All lifecycle management past that point must be handled by the client. (For details on the
lifecycle of a bean in the Spring container, see Lifecycle Callbacks.)

Singleton Beans with Prototype-bean


Dependencies
When you use singleton-scoped beans with dependencies on prototype beans, be aware that dependencies
are resolved at instantiation time. Thus, if you dependency-inject a prototype-scoped bean into a singleton-
scoped bean, a new prototype bean is instantiated and then dependency-injected into the singleton bean. The
prototype instance is the sole instance that is ever supplied to the singleton-scoped bean.

However, suppose you want the singleton-scoped bean to acquire a new instance of the prototype-scoped
bean repeatedly at runtime. You cannot dependency-inject a prototype-scoped bean into your singleton bean,
because that injection occurs only once, when the Spring container instantiates the singleton bean and
resolves and injects its dependencies. If you need a new instance of a prototype bean at runtime more than
once, see Method Injection.

https://docs.spring.io/spring-framework/reference/core/beans/factory-scopes.html 3/8
06/12/2023, 15:55 Bean Scopes :: Spring Framework

Request, Session, Application, and


WebSocket Scopes
The request , session , application , and websocket scopes are available only if you use a web-aware
Spring ApplicationContext implementation (such as XmlWebApplicationContext ). If you use these scopes with
regular Spring IoC containers, such as the ClassPathXmlApplicationContext , an IllegalStateException that
complains about an unknown bean scope is thrown.

Initial Web Configuration


To support the scoping of beans at the request , session , application , and websocket levels (web-scoped
beans), some minor initial configuration is required before you define your beans. (This initial setup is not
required for the standard scopes: singleton and prototype .)

How you accomplish this initial setup depends on your particular Servlet environment.

If you access scoped beans within Spring Web MVC, in effect, within a request that is processed by the
Spring DispatcherServlet , no special setup is necessary. DispatcherServlet already exposes all relevant
state.

If you use a Servlet web container, with requests processed outside of Spring’s DispatcherServlet (for
example, when using JSF), you need to register
the org.springframework.web.context.request.RequestContextListener ServletRequestListener . This can be
done programmatically by using the WebApplicationInitializer interface. Alternatively, add the following
declaration to your web application’s web.xml file:

<web-app>
...
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
...
</web-app>

Alternatively, if there are issues with your listener setup, consider using Spring’s RequestContextFilter . The
filter mapping depends on the surrounding web application configuration, so you have to change it as
appropriate. The following listing shows the filter part of a web application:

<web-app>
...
<filter>
<filter-name>requestContextFilter</filter-name>
<filter-class>org.springframework.web.filter.RequestContextFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>requestContextFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
https://docs.spring.io/spring-framework/reference/core/beans/factory-scopes.html 4/8
06/12/2023, 15:55 Bean Scopes :: Spring Framework

...
</web-app>

DispatcherServlet , RequestContextListener , and RequestContextFilter all do exactly the same thing, namely
bind the HTTP request object to the Thread that is servicing that request. This makes beans that are request-
and session-scoped available further down the call chain.

Request scope
Consider the following XML configuration for a bean definition:

<bean id="loginAction" class="com.something.LoginAction" scope="request"/>

The Spring container creates a new instance of the LoginAction bean by using the loginAction bean
definition for each and every HTTP request. That is, the loginAction bean is scoped at the HTTP request
level. You can change the internal state of the instance that is created as much as you want, because other
instances created from the same loginAction bean definition do not see these changes in state. They are
particular to an individual request. When the request completes processing, the bean that is scoped to the
request is discarded.

When using annotation-driven components or Java configuration, the @RequestScope annotation can be
used to assign a component to the request scope. The following example shows how to do so:

Java Kotlin

@RequestScope
@Component
public class LoginAction {
// ...
}

Session Scope
Consider the following XML configuration for a bean definition:

<bean id="userPreferences" class="com.something.UserPreferences" scope="session"/>

The Spring container creates a new instance of the UserPreferences bean by using
the userPreferences bean definition for the lifetime of a single HTTP Session . In other words,
the userPreferences bean is effectively scoped at the HTTP Session level. As with request-scoped beans,
you can change the internal state of the instance that is created as much as you want, knowing that other
HTTP Session instances that are also using instances created from the same userPreferences bean
definition do not see these changes in state, because they are particular to an individual HTTP Session .
When the HTTP Session is eventually discarded, the bean that is scoped to that particular HTTP Session is
also discarded.

When using annotation-driven components or Java configuration, you can use


the @SessionScope annotation to assign a component to the session scope.

Java Kotlin
https://docs.spring.io/spring-framework/reference/core/beans/factory-scopes.html 5/8
06/12/2023, 15:55 Bean Scopes :: Spring Framework

@SessionScope
@Component
public class UserPreferences {
// ...
}

Application Scope
Consider the following XML configuration for a bean definition:

<bean id="appPreferences" class="com.something.AppPreferences" scope="application"/>

The Spring container creates a new instance of the AppPreferences bean by using the appPreferences bean
definition once for the entire web application. That is, the appPreferences bean is scoped at
the ServletContext level and stored as a regular ServletContext attribute. This is somewhat similar to a
Spring singleton bean but differs in two important ways: It is a singleton per ServletContext , not per
Spring ApplicationContext (for which there may be several in any given web application), and it is actually
exposed and therefore visible as a ServletContext attribute.

When using annotation-driven components or Java configuration, you can use


the @ApplicationScope annotation to assign a component to the application scope. The following example
shows how to do so:

Java Kotlin

@ApplicationScope
@Component
public class AppPreferences {
// ...
}

WebSocket Scope
WebSocket scope is associated with the lifecycle of a WebSocket session and applies to STOMP over
WebSocket applications, see WebSocket scope for more details.

Scoped Beans as Dependencies


The Spring IoC container manages not only the instantiation of your objects (beans), but also the wiring up of
collaborators (or dependencies). If you want to inject (for example) an HTTP request-scoped bean into
another bean of a longer-lived scope, you may choose to inject an AOP proxy in place of the scoped bean.
That is, you need to inject a proxy object that exposes the same public interface as the scoped object but that
can also retrieve the real target object from the relevant scope (such as an HTTP request) and delegate
method calls onto the real object.

https://docs.spring.io/spring-framework/reference/core/beans/factory-scopes.html 6/8
06/12/2023, 15:55 Bean Scopes :: Spring Framework

You may also use <aop:scoped-proxy/> between beans that are scoped as singleton , with the
reference then going through an intermediate proxy that is serializable and therefore able to re-
obtain the target singleton bean on deserialization.

When declaring <aop:scoped-proxy/> against a bean of scope prototype , every method call on the
shared proxy leads to the creation of a new target instance to which the call is then being forwarded.

Also, scoped proxies are not the only way to access beans from shorter scopes in a lifecycle-safe
fashion. You may also declare your injection point (that is, the constructor or setter argument or
autowired field) as ObjectFactory<MyTargetBean> , allowing for a getObject() call to retrieve the
current instance on demand every time it is needed — without holding on to the instance or storing it
separately.

As an extended variant, you may declare ObjectProvider<MyTargetBean> which delivers several


additional access variants, including getIfAvailable and getIfUnique .

The JSR-330 variant of this is called Provider and is used with


a Provider<MyTargetBean> declaration and a corresponding get() call for every retrieval attempt.
See here for more details on JSR-330 overall.

The configuration in the following example is only one line, but it is important to understand the “why” as well
as the “how” behind it:

<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">

<!-- an HTTP Session-scoped bean exposed as a proxy -->


<bean id="userPreferences" class="com.something.UserPreferences" scope="session">
<!-- instructs the container to proxy the surrounding bean -->
<aop:scoped-proxy/>
</bean>

<!-- a singleton-scoped bean injected with a proxy to the above bean -->
<bean id="userService" class="com.something.SimpleUserService">
<!-- a reference to the proxied userPreferences bean -->
<property name="userPreferences" ref="userPreferences"/>
</bean>
</beans>

The line that defines the proxy.

To create such a proxy, you insert a child <aop:scoped-proxy/> element into a scoped bean definition
(see Choosing the Type of Proxy to Create and XML Schema-based configuration).

Why do definitions of beans scoped at the request , session and custom-scope levels require
the <aop:scoped-proxy/> element in common scenarios? Consider the following singleton bean definition and
contrast it with what you need to define for the aforementioned scopes (note that the
following userPreferences bean definition as it stands is incomplete):

https://docs.spring.io/spring-framework/reference/core/beans/factory-scopes.html 7/8
06/12/2023, 15:55 Bean Scopes :: Spring Framework

<bean id="userPreferences" class="com.something.UserPreferences" scope="session"/>

<bean id="userManager" class="com.something.UserManager">


<property name="userPreferences" ref="userPreferences"/>
</bean>

In the preceding example, the singleton bean ( userManager ) is injected with a reference to the
HTTP Session -scoped bean ( userPreferences ). The salient point here is that the userManager bean is a
singleton: it is instantiated exactly once per container, and its dependencies (in this case only one,
the userPreferences bean) are also injected only once. This means that the userManager bean operates
only on the exact same userPreferences object (that is, the one with which it was originally injected).

This is not the behavior you want when injecting a shorter-lived scoped bean into a longer-lived scoped bean
(for example, injecting an HTTP Session -scoped collaborating bean as a dependency into singleton bean).
Rather, you need a single userManager object, and, for the lifetime of an HTTP Session , you need
a userPreferences object that is specific to the HTTP Session . Thus, the container creates an object that
exposes the exact same public interface as the UserPreferences class (ideally an object that is
a UserPreferences instance), which can fetch the real UserPreferences object from the scoping mechanism
(HTTP request, Session , and so forth). The container injects this proxy object into the userManager bean,
which is unaware that this UserPreferences reference is a proxy. In this example, when
a UserManager instance invokes a method on the dependency-injected UserPreferences object, it is actually
invoking a method on the proxy. The proxy then fetches the real UserPreferences object from (in this case)
the HTTP Session and delegates the method invocation onto the retrieved real UserPreferences object.

Thus, you need the following (correct and complete) configuration when injecting request- and session-
scoped beans into collaborating objects, as the following example shows:

<bean id="userPreferences" class="com.something.UserPreferences" scope="session">


<aop:scoped-proxy/>
</bean>

<bean id="userManager" class="com.something.UserManager">


<property name="userPreferences" ref="userPreferences"/>
</bean>

https://docs.spring.io/spring-framework/reference/core/beans/factory-scopes.html 8/8

You might also like