Spring Bean Scopes
Spring Bean Scopes define the lifecycle and visibility of beans within the Spring IoC container. This overview covers the different types of bean scopes available in Spring and how to use them effectively.
Types of Bean Scopes
- Singleton: A single shared instance of the bean is created and managed by the Spring container. This is the default scope.
- Prototype: A new instance of the bean is created each time it is requested from the container.
- Request: A new instance of the bean is created for each HTTP request. This scope is available in a web-aware Spring application context.
- Session: A new instance of the bean is created for each HTTP session. This scope is available in a web-aware Spring application context.
- Global Session: A new instance of the bean is created for each global HTTP session. This scope is available in a web-aware Spring application context.
- Application: A single shared instance of the bean is created and managed at the servlet context level. This scope is also available in a web-aware Spring application context.
- WebSocket: A new instance of the bean is created for each WebSocket session.
Setting Bean Scopes
Bean scopes can be set using annotations or XML configuration. Here are examples of both methods:
Using Annotations
// MyService.java
package com.example.springbeanscopes;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
@Service
@Scope("prototype")
public class MyService {
public void performTask() {
System.out.println("Performing a task in MyService.");
}
}
Using XML Configuration
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="myService" class="com.example.springbeanscopes.MyService" scope="prototype"/>
</beans>
Singleton Scope
The singleton scope is the default scope in Spring. A single instance of the bean is created and shared across the entire Spring context.
// AppConfig.java
package com.example.springbeanscopes;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
Prototype Scope
The prototype scope creates a new instance of the bean each time it is requested from the container.
// AppConfig.java
package com.example.springbeanscopes;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
@Configuration
public class AppConfig {
@Bean
@Scope("prototype")
public MyService myService() {
return new MyService();
}
}
Web-Aware Scopes
Web-aware scopes include request, session, application, and WebSocket scopes. These scopes are available only in a web-aware Spring application context.
Request Scope
// MyController.java
package com.example.springbeanscopes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Scope(WebApplicationContext.SCOPE_REQUEST)
public class MyController {
@Autowired
private MyService myService;
@GetMapping("/task")
public String performTask() {
myService.performTask();
return "Task performed";
}
}
Session Scope
// MyController.java
package com.example.springbeanscopes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Scope(WebApplicationContext.SCOPE_SESSION)
public class MyController {
@Autowired
private MyService myService;
@GetMapping("/task")
public String performTask() {
myService.performTask();
return "Task performed";
}
}
Custom Scopes
Spring also allows the creation of custom scopes. Here is an example of a custom scope:
Custom Scope Implementation
// CustomScope.java
package com.example.springbeanscopes;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
public class CustomScope implements Scope {
private Map scopedObjects = new HashMap<>();
@Override
public Object get(String name, ObjectFactory> objectFactory) {
return scopedObjects.computeIfAbsent(name, k -> objectFactory.getObject());
}
@Override
public Object remove(String name) {
return scopedObjects.remove(name);
}
@Override
public void registerDestructionCallback(String name, Runnable callback) {
// No implementation needed for this example
}
@Override
public Object resolveContextualObject(String key) {
return null;
}
@Override
public String getConversationId() {
return "custom";
}
}
// AppConfig.java
package com.example.springbeanscopes;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.support.SimpleThreadScope;
@Configuration
public class AppConfig {
@Bean
public CustomScope customScope() {
return new CustomScope();
}
@Bean
@Scope(scopeName = "custom", proxyMode = ScopedProxyMode.TARGET_CLASS)
public MyService myService() {
return new MyService();
}
}
Key Points
- Spring Bean Scopes define the lifecycle and visibility of beans within the Spring IoC container.
- The most commonly used scopes are singleton and prototype. Singleton is the default scope.
- Web-aware scopes include request, session, application, and WebSocket scopes, and are available only in a web-aware Spring application context.
- Spring allows the creation of custom scopes to handle specific use cases.
- Bean scopes can be set using annotations or XML configuration.
Conclusion
Understanding Spring Bean Scopes is crucial for managing the lifecycle and visibility of beans within your application. By leveraging different scopes, developers can control how beans are created and shared, ensuring the application behaves as expected. Happy coding!