第八章-Spring Bean 作用域
程序员文章站
2022-05-27 16:06:36
...
Spring Bean 作用域
来源 | 说明 |
singleton | 默认 Spring Bean 作用域,一个 BeanFactory 有且仅有一个实例 |
prototype | 原型作用域,每次依赖查找和依赖注入生成新 Bean 对象 |
request | 将 Spring Bean 存储在 ServletRequest 上下文中 |
session | 将 Spring Bean 存储在 HttpSession 中 |
application | 将 Spring Bean 存储在 ServletContext 中 |
“singleton” Bean 作用域
“prototype” Bean 作用域
“prototype” Bean 作用域
Spring 容器没有办法管理 prototype Bean 的完整生命周期,也没有办法记录示例的存
在。销毁回调方法将不会执行,可以利用 BeanPostProcessor 进行清扫工作。
“request” Bean 作用域
配置
- XML -
- Java 注解 - @RequestScope 或@Scope(WebApplicationContext.SCOPE_REQUEST)
实现
API - RequestScope
“session” Bean 作用域
- XML -
- Java 注解 - @RequestScope 或@Scope(WebApplicationContext.SCOPE_REQUEST)
实现
API - SessionScope
“application” Bean 作用域
- XML -
- Java 注解 - @ApplicationScope 或 @Scope(WebApplicationContext.SCOPE_APPLICATION)
实现
• API - ApplicationScope
自定义 Bean 作用域
实现 Scope
- org.springframework.beans.factory.config.Scope
- 注册 Scope
API -org.springframework.beans.factory.config.ConfigurableBeanFactory#registerScope - 配置
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
<property name="scopes">
<map>
<entry key="...">
</entry>
</map>
</property>
</bean>