我有一个spring应用程序。我有一个bean,它连接为一个单例,也是一个字段,它也是自动设置的,但具有请求范围。例如:
class Hello {
@Autowired
BDepend b; // this is defined as a request scope bean
@Autowired
public Hello(ADepend a){
}
}在这里,我的类Hello是一个单例,但是BDepend是一个请求作用域对象。spring对每个请求如何处理正确的实例,因为Hello是一个单例。
发布于 2013-07-23 15:55:42
默认情况下,应用程序安装时将出现运行时异常。就像这样:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'b': Scope 'request' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton;
要在一些单例中使用请求作用域对象,您需要每次从应用程序上下文中获取一个新的实例。你可以这样做:
javax.inject.Provider获得一个新实例。
类Hello { @Autowired私有提供者提供程序;@Autowired Hello(ADepend A)}{ BDepend useB(){ BDepend实例= this.provider.get();instance.doSomething();}就我个人而言,我更喜欢第二个选项(javax.inject.Provider):从代码中可以清楚地看到,您的bean具有不同的范围。
https://stackoverflow.com/questions/17812192
复制相似问题