将会话范围的bean自动装入线程(Spring) [英] Autowire session-scoped bean into thread (Spring)

查看:168
本文介绍了将会话范围的bean自动装入线程(Spring)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Spring中有一个会话范围的bean,它在web上下文中设置。我有一个作为Callable运行的任务,我需要从该线程中访问这个bean。我该怎么做到这一点?如果我只是尝试自动装配bean,我会收到错误消息:

I have a session-scoped bean in Spring that is set within the web context. I have a task that runs as a Callable, and I need access to this bean from within that thread. How should I accomplish this? If I simply attempt autowiring the bean I get the error message:


当前线程的会话范围不活动

Scope 'session' is not active for the current thread

我注入的会话范围的bean看起来像这样:

The session-scoped bean I am injecting looks like this:

<bean id="userInfo" class="com.company.web.UserInfoBean" scope="session">
    <aop:scoped-proxy />
</bean>

我试图将它注入的类看起来像这样:

And the class I am trying to inject it into looks like this:

@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正在启动这个:

Lastly, the Callable is being started up like this:

@Autowired
private GenerateExportThread generateExportThread;

@Autowired
private AsyncTaskExecutor taskExecutor;

public void myMethod() {
...
    Future<String> future = taskExecutor.submit( new ThreadScopeCallable<String>( generateExportThread ) );
...
}

ISubmissionDao实现被正确注入,但不是它的UserInfoBean,因为该bean是会话范围的。我可以做一些手动代码工作,如果有必要在线程启动时将对象从一个会话复制到另一个会话(如果这是有意义的)但我只是不知道如何去做这个。任何提示都表示赞赏。谢谢!

The ISubmissionDao implementation gets injected correctly, but not its UserInfoBean because that bean is session-scoped. I am okay with doing some manual code work if necessary to copy the object from one session into another at thread startup time (if this makes sense) but I just don't know how to go about doing this. Any tips are appreciated. Thanks!

推荐答案

手动注射:

你的线程范围bean:

Your thread-scoped 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

这篇关于将会话范围的bean自动装入线程(Spring)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆