常见的 4 种作用域
Spring Bean 的默认作用域是 Singleton。一般通过注解 @Scope 自定义Bean的作用域。
-
Singleton 整个应用中,只创建一个实例。(默认)
ConfigurableBeanFactory.SCOPE_SINGLETON
-
Prototype 每次注入或通过Spring Application Context 获取时,都会创建一个新的实例
ConfigurableBeanFactory.SCOPE_PROTOTYPE
-
Session 在 Web 应用中,为每个会话创建一个实例
WebApplicationContext.SCOPE_SESSION
-
Request 在 Web 应用中,为每个请求创建一个实例
WebApplicationContext.SCOPE_REQUEST
注入 Session、Request 作用域的 Bean
通常较少直接用到这类作用域的Bean。
一般会在 RestController 类中使用。
可以属性/字段注入的方式获取,也可以方法参数注入的方式获取。
Java代码
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnLxkjM0AzN1MTM5ATMwAjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
- @RestController
- public class TestController {
- // 以字段注入的方式获取
- @Autowired
- private ServletRequest request;
- // 以方法参数注入的方式获取
- @GetMapping("/func")
- public void func(ServletRequest request) {
- ...
- }
- }
Spring Web 框架中的关键代码
spring-web 5.1.5.RELEASE
Java代码
- public abstract class WebApplicationContextUtils {
- public static void registerWebApplicationScopes(
- ConfigurableListableBeanFactory beanFactory,
- @Nullable ServletContext sc) {
- beanFactory.registerScope(
- WebApplicationContext.SCOPE_REQUEST, new RequestScope());
- beanFactory.registerScope(
- WebApplicationContext.SCOPE_SESSION, new SessionScope());
- if (sc != null) {
- ServletContextScope appScope = new ServletContextScope(sc);
- beanFactory.registerScope(
- WebApplicationContext.SCOPE_APPLICATION, appScope);
- // Register as ServletContext attribute, for ContextCleanupListener to detect it.
- sc.setAttribute(ServletContextScope.class.getName(), appScope);
- }
- beanFactory.registerResolvableDependency(
- ServletRequest.class, new RequestObjectFactory());
- beanFactory.registerResolvableDependency(
- ServletResponse.class, new ResponseObjectFactory());
- beanFactory.registerResolvableDependency(
- HttpSession.class, new SessionObjectFactory());
- beanFactory.registerResolvableDependency(
- WebRequest.class, new WebRequestObjectFactory());
- if (jsfPresent) {
- FacesDependencyRegistrar.registerFacesDependencies(beanFactory);
- }
- }
- }