Autowire session-scoped bean into thread (Spring)

孤人 提交于 2019-12-08 07:36:08

问题


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

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;
  ...
}

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 ) );
...
}

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!


回答1:


Do manual injection:

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;
    }
    ...
}

On your request thread:

...
@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


来源:https://stackoverflow.com/questions/9184068/autowire-session-scoped-bean-into-thread-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!