注解说明
- singleton 全局只有一个实例,即单例模式
- prototype 每次注入Bean都是一个新的实例
- request 每次HTTP请求都会产生新的Bean
- session 每次HTTP请求都会产生新的Bean,该Bean在仅在当前session内有效
- global session 每次HTTP请求都会产生新的Bean,该Bean在 当前global Session(基于portlet的web应用中)内有效
引入步骤
在类上加入@Scope注解,指定使用的模式,默认是单例模式
示例代码
单例模式示例
在两个MysScopeTest中都注入MyScope,测试结果可以发现两个MyScopeTest中的MyScope是同一个。
1 | import org.springframework.context.annotation.Scope; |
1 | import org.springframework.beans.factory.annotation.Autowired; |
1 | import org.springframework.beans.factory.annotation.Autowired; |
原型模式示例
在两个MysScopeTest中都注入MyScope,测试结果可以发现两个MyScopeTest中的MyScope不是同一个。
1 | import org.springframework.context.annotation.Scope; |