Spring Boot Tutorial
Spring Boot - Software Setup and Configuration (STS/Eclipse/IntelliJ)
Prerequisite (Spring Core Concepts)
Spring Boot Core
Spring Boot with REST API
Spring Boot with Database and Data JPA
Spring Boot with Kafka
Spring Boot with AOP
In Spring, bean scopes determine the lifecycle and the uniqueness of a bean within the Spring container. The two most common bean scopes are singleton
and prototype
.
singleton
):When a bean is defined as a singleton, the Spring IoC container creates exactly one instance of the bean. This single instance is stored in the container and is reused each time that specific bean is requested. The singleton
scope is the default scope in Spring.
Characteristics:
Example:
<bean id="mySingletonBean" class="com.example.MyClass" scope="singleton"/>
Or, using Java configuration:
@Bean @Scope("singleton") public MyClass mySingletonBean() { return new MyClass(); }
prototype
):When a bean is defined as a prototype, the Spring IoC container creates a new bean instance every time a request for that bean is made. This is opposite to the singleton scope where only a single instance is reused.
Characteristics:
Example:
<bean id="myPrototypeBean" class="com.example.MyClass" scope="prototype"/>
Or, using Java configuration:
@Bean @Scope("prototype") public MyClass myPrototypeBean() { return new MyClass(); }
Singleton
: A single instance is created and managed by the Spring container. This instance is shared and returned for each bean request.Prototype
: A new instance is created every time the bean is requested.Singleton
: Since there's only one instance, memory consumption is limited regardless of how many times the bean is requested.Prototype
: Since a new instance is created upon every request, excessive use might lead to higher memory consumption.Singleton
: Useful for stateless beans or services where you don't maintain any state between client requests.Prototype
: Useful for stateful beans where each request expects a different behavior or result.For singleton
scoped beans, Spring takes care of the complete lifecycle, from creation to destruction. However, for prototype
scoped beans, Spring only manages the initial creation. The destruction lifecycle callbacks (like @PreDestroy
) are not called for prototype beans because the Spring container doesn't have a reference to the prototype bean once it's handed over to the client. It's the client's responsibility to manage the rest of the bean's lifecycle.