如何使用自定义范围和@Autowired依赖关系实例化Spring bean? [英] How to instantiate Spring bean with custom scope and @Autowired dependencies?
问题描述
在我们的项目中,我们使用Spring请求范围的bean.现在,我们需要支持异步请求,并且请求范围的Bean不适用于子线程.我知道 RequestContextFilter ,它是异步的支持",但似乎RequestContextFilter
希望主线程等待子线程完成,而对我们而言并非如此.我们的主线程在使用@Async
注释生成新线程之后立即返回,并且DispatcherServlet
清除了RequestContextHolder
.因此,当子线程到达需要它们的请求范围的Bean时,@Autowired
就会失败.
In our project, we use Spring request scoped beans. Now we've a requirement to support async requests and request scoped beans don't work for child threads. I'm aware of RequestContextFilter and it's "support" for async but it appears that RequestContextFilter
expects the main thread to wait for the child threads to finish, which isn't the case for us. Our main thread immediately returns after spawning new threads using @Async
annotation and DispatcherServlet
clears out the RequestContextHolder
. Thus when the child threads get to the point where they need a request scoped bean, @Autowired
fails.
I'm also aware of SimpleThreadScope but it doesn't clean up thread-local attributes and in a thread-pooling situation, is not only dangerous to use but downright useless.
我需要的是自定义范围.到目前为止,我已经找到了3个有用的示例,但是它们都不足,因为它们实例化为自定义范围一部分的bean是没有任何依赖关系的普通POJO.不用说这在现实生活中是不存在的.谁能提出一种实例化自定义范围的Bean的方法,该范围在其他范围内对Bean具有@Autowired
依赖性?
What I need is a custom scope. So far, I've found 3 useful examples but all of them fall short in that the beans they instantiate as part of the custom scope are plain POJOs without any dependencies. Needless to say that's non-existent in a real life application. Can anyone suggest a way to instantiate custom scoped beans that have @Autowired
dependencies on beans from other scopes?
到目前为止我发现了什么
What I found so far:
https://github.com/billkoch/spring-async-mdc