[英]Autowire session-scoped bean into thread (Spring)
我在Spring中有一个会话范围的bean,它在Web上下文中设置。 我有一个作为Callable运行的任务,我需要从该线程内访问此bean。 我应该如何做到这一点? 如果我只是尝试自动装配Bean,我会收到错误消息:
作用域“会话”对于当前线程无效
我正在注入的会话范围的bean看起来像这样:
<bean id="userInfo" class="com.company.web.UserInfoBean" scope="session">
<aop:scoped-proxy />
</bean>
我正在尝试将其注入类中,如下所示:
@Component
@Scope( value = "thread", proxyMode = ScopedProxyMode.TARGET_CLASS )
public class GenerateExportThread implements Callable<String> {
...
// this class contains an @Autowired UserInfoBean
@Autowired
private ISubmissionDao submissionDao;
...
}
最后,Callable正在这样启动:
@Autowired
private GenerateExportThread generateExportThread;
@Autowired
private AsyncTaskExecutor taskExecutor;
public void myMethod() {
...
Future<String> future = taskExecutor.submit( new ThreadScopeCallable<String>( generateExportThread ) );
...
}
ISubmissionDao实现可以正确注入,但不能正确注入它的UserInfoBean,因为该bean是基于会话作用域的。 如果有必要,我可以做一些手动代码工作,以便在线程启动时将对象从一个会话复制到另一个会话中(如果这是有道理的),但是我只是不知道该怎么做。 任何提示表示赞赏。 谢谢!
进行手动注射:
您的线程范围的bean:
@Component
@Scope( value = "thread", proxyMode = ScopedProxyMode.TARGET_CLASS )
public class GenerateExportThread implements Callable<String> {
...
// this class contains an @Autowired UserInfoBean
private ISubmissionDao submissionDao;
public void setSubmissionDao(ISubmissionDao submissionDao) {
this.submissionDao = submissionDao;
}
...
}
在您的请求线程上:
...
@Autowired // This should work as a request has an implicit session
private ISubmissionDao submissionDao;
@Autowired // This should also work: the request thread should have a thread-scoped exportThread
private GenerateExportThread generateExportThread;
...
generateExportThread.setSubmissionDao(submissionDao);
String result = generateExportThread.call(); // Or whatever you use to run this thread
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.