Spring Framework Tutorial
Software Setup and Configuration (STS/Eclipse/IntelliJ)
Core Spring
Spring Annotations
Spring Data
Spring JDBC
Spring Security
In Spring Framework, beans can be defined with different scopes which determine their lifecycle and their uniqueness in the application context. Two of the most commonly used bean scopes are Singleton and Prototype.
singleton
):When a bean is defined with Singleton scope:
Example in XML Configuration:
<bean id="exampleBean" class="com.example.ExampleBean" scope="singleton"/>
Example in Java Configuration:
@Bean @Scope("singleton") public ExampleBean exampleBean() { return new ExampleBean(); }
prototype
):Example in XML Configuration:
<bean id="exampleBean" class="com.example.ExampleBean" scope="prototype"/>
Example in Java Configuration:
@Bean @Scope("prototype") public ExampleBean exampleBean() { return new ExampleBean(); }
Instance Creation:
Memory Consumption:
Statefulness:
Lifecycle:
It's important to understand the needs of your application and the beans within it to select the appropriate scope.
Java Spring @Scope annotation usage:
The @Scope
annotation in Spring is used to declare the scope of a bean.
Example using @Scope
for a Singleton bean:
@Component @Scope("singleton") public class MySingletonBean { // Singleton bean logic }
Example using @Scope
for a Prototype bean:
@Component @Scope("prototype") public class MyPrototypeBean { // Prototype bean logic }
Managing bean scopes in Spring applications:
Bean scopes are managed through the Spring configuration, either using annotations or XML configuration.
Example XML configuration for a Singleton bean:
<bean id="singletonBean" class="com.example.MySingletonBean" scope="singleton"/>
Example XML configuration for a Prototype bean:
<bean id="prototypeBean" class="com.example.MyPrototypeBean" scope="prototype"/>
Singleton vs. Prototype in Spring with examples:
Example illustrating the use of a Singleton bean:
@Service public class MySingletonService { // Singleton service logic }
Example illustrating the use of a Prototype bean:
@Component @Scope("prototype") public class MyPrototypeComponent { // Prototype component logic }
In this scenario, the MySingletonService
will be a single shared instance, while each injection of MyPrototypeComponent
will result in a new instance.