Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 (e.g. 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?

like image 298
benjamin.donze Avatar asked Nov 24 '25 19:11

benjamin.donze


1 Answers

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 (i.e. background task) and should be exclusive to your web-app.

Refer relevant java docs here, here and here.

like image 167
Bond - Java Bond Avatar answered Nov 26 '25 08:11

Bond - Java Bond