我在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是会话范围的。我可以做一些手动代码工作,如果有必要在线程启动时将对象从一个会话复制到另一个会话(如果这是有道理的)但我只是不知道如何去做这个。任何提示都表示赞赏。谢谢!
答案 0 :(得分:4)
手动注射:
你的线程范围的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