Replace scoped session bean for background task

In my web-application I have a scoped session bean that is used among other things to keep some credential information required to connect to underlying systems (store a SAML that need to be sent for underlying web-services access).

And I have that bean that does inject the credential at the right place right before the call to the web-serivce.

@Autowired
private MyScopedSession myScopedSession;
@Autowired
private SomeWebService someWebService;

public void someCall() {
  ...
  injectSamlPart
  ...
}

I want to add background task (one war packaging both web-app + some background task) that runs every hour for this I use a scheduler. Problem is that this background task can't use scoped-session bean (make sense as it is not driven by http request). So I get this kind of error:

Scope 'session' is not active for the current thread;

But I'd like to define a static credential for my background task (eg define a system account or so) and thus define a kind of a replacement bean MyScopedSession for the background task so that autowiring works. Is this possible?

For sure what I could do is to define my bean as

@Autowired
private SomeWebService someWebService;

public void someCall(MyScopedSession myScopeSession) {
  ...
  injectSamlPart
  ...
}

But I don't like this much as I don't want to pass by parameter my credential through all my business services (maybe 10 layers of beans over this up to my background tasks, or up to my rpc calls)

Is there any solution or architecture change that you could recommend?


If your scheduled task are triggered within spring context you can register Session scope as ThreadScope with below two LOC

ConfigurableBeanFactory factory = applicationContext.getBeanFactory();
factory.registerScope(WebApplicationContext.SCOPE_SESSION,
                    new SimpleThreadScope());

This should be done at start / initialization of your application (ie background task) and should be exclusive to your web-app.

Refer relevant java docs here, here and here.

链接地址: http://www.djcxy.com/p/38930.html

上一篇: 安排电子邮件以便稍后在Web应用程序中发送

下一篇: 替换后台任务的作用域会话bean