2017-05-30 41 views
1

我只是想知道是否有其他方式來自動裝載請求作用域bean。所以現在我在配置文件中創建一個bean自動裝配請求作用域bean的方法

@Bean 
@Scope(value=WebApplicationContext.SCOPE_REQUEST, proxyMode=ScopedProxyMode.DEFAULT) 
public List<String> stringBean(){ 
    return new ArrayList<String>(); 
} 

所以通常我會自動裝配的applicationContext使用bean

@Autowired 
private ApplicationContext context; 

@Override 
public void anyName() { 
    List<String> list = (List<String>) getContext().getBean("stringBean"); 
} 

這工作完全正常。但我不喜歡自動調整背景和演員的需要。於是,我就直接自動裝配豆:

@Autowired 
private List<String> stringBean; 

我得到了應用程序是什麼也很清楚,因爲一個請求開始之前沒有創建bean的啓動異常。

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'stringBean': 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; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request. 

是否有其他方式自動裝入請求作用域bean?

+1

'ScopedProxyMode.DEFAULT',如果您還沒有配置任何,意味着NO (沒有創建代理)。嘗試使用'ScopedProxyMode.TARGET_CLASS'來使用'CGLIB'代理。 – alfcope

+0

@alfcope看起來像這樣工作。你能解釋一下不同嗎?也可以在答案中。 – Patrick

+0

當然,你有。這完全是關於代理。 – alfcope

回答

3

ScopedProxyMode.DEFAULT,如果你還沒有配置任何,意味着NO(沒有創建代理)。嘗試使用ScopedProxyMode.TARGET_CLASS以便使用CGLIB代理

正如您已經知道的,單例bean僅創建一次,並且它們的依賴注入是在初始化時進行的。正如你在你的問題中所說的那樣,對於請求作用域的bean來說,那時bean不存在,你會得到異常。

爲了避免這種情況,您需要讓Spring知道您想要使用代理bean。代理bean只是Spring動態創建的一個bean,並且公開與您所定位的公共接口相同的公共接口。這個代理bean是Spring將要在你的bean中注入的一個代理bean,當調用它的方法時,會將調用委託給爲該請求創建的實際調用。

當使用接口(ScopedProxyMode.INTERFACES)或CGLIBScopedProxyMode.TARGET_CLASS)時,有兩種代理機制:JDK dynamic proxies

我希望你明白。

看一看一些有用的文檔:

Scoped beans as dependencies

Choosing the type of proxy to create

Proxying mechanisms

Aspect Oriented Programming with Spring

相關問題