Spring注解设置bean⾮单例
概述
通过Spring管理的类,默认是单例模式,但是如果有的类需要使⽤独⽴的属性,则需要配置为多例模式的.但是多例模式不仅仅只是加⼀个声明,使⽤@Autowired进⾏注⼊,可能并不会是你想要的结果.因为多例模式的类是需要单独调⽤的.
不搞清楚原理直接测试:
需要多例的类上加上注解@Scope(“prototype”)
@Component
@Scope("prototype")
public class ExampleService{
public void test(){
System.out.println("test,current bean is"+this);
}
}
引⽤直接使⽤@Autowired
@Controller
public class ExampleService{
@Autowired
private ExampleService exampleService;
@RequestMapping("test")
public void test(){
}
}
结果:每个request过来的时候,exampleService实例均为同⼀个实例.
解决办法:
第⼀种:不使⽤@Autowired
@Controller
public class ExampleService{
@Autowired
private org.springframework.beans.factory.BeanFactory beanFactory;
@RequestMapping("test")
public void test(){
ExampleService exampleService = Bean(ExampleService.class);
}
}
第⼆种:使⽤bean⼯⼚
controller单例还是多例@Autowired
private ApplicationContext context;
@Bean
public WebSocketHandler websocketBHandler(){
PerConnectionWebSocketHandler perConnectionHandler =new PerConnectionWebSocketHandler(WebSocketBHandler.class);
perConnectionHandler.AutowireCapableBeanFactory());
//设置bean⼯⼚,否则bean⼯⼚WebSocketBHandler将不会⾃动连接
return perConnectionHandler;
return perConnectionHandler;
}
然后使⽤ApplicationContext进⾏代理bean⼯⼚
注⼊
@Autowired
private ApplicationContext context;
使⽤
this.Bservice = Bean(BService.class,this);
官⽅⽂档说明
4.5.3 Singleton beans with prototype-bean dependencies When you use singleton-scoped beans with
dependencies on prototype beans, be aware that de pendencies are resolved at instantiation time. Thus if you dependency-inject a prototype-scoped bean into a singleton-scoped bean, a new prototype bean is instantiated and then dependency-injected into the singleton bean. The prototype instance is the sole instance that is ever supplied to the singleton-sco ped bean. However, suppose you want the singleton-scoped bean to acquire a new instance of the prototype-scoped bean repeatedly at runtime. You can not dependency-inject a prototype-scoped bean into your singleton bean, because that injection occurs only once, when the Spring container is instantiatin
g the singleton bean and resolving and injecting its dependencies. If you need a new instance of a prototype bean at runtime more than once, see Section
4.4.6, “Method injection”
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论