views:

109

answers:

2

Is it possible to create a factory or proxy that can decide if thread is running in (Web)Request or background-process (ie. scheduler) and then depending on that information, it creates a session bean or a prototype bean?

Example (pseudo Spring config :)

<bean id="userInfoSession" scope="session" />
<bean id="userInfoStatic" scope="prototype" />

<bean id="currentUserInfoFactory" />

<bean id="someService" class="...">
    <property name="userInfo" ref="currentUserInfoFactory.getCurrentUserInfo()" />
</bean>

I hope this makes my question easier to understand...

A: 

Your rephrase is indeed considerably simpler :)

Your currentUserInfoFactory could make use of RequestContextHolder.getRequestAttributes(). If a session is present and associated with the calling thread, then this will return a non-null object, and you can then safely retrieve the session-scoped bean from the context. If it returns a null, then you should fetch the prototype-scoped bean instead.

It's not very neat, but it's simple, and should work.

skaffman
I will try it. Sometimes the simplest solution is the best and if it works, why isn't it neat? Some other solutions?
Frank Szilinski
@Frank: Code that uses `RequestContextHolder` is generally hard to test. For that reason, it should be discouraged.
skaffman
A: 

Create two custom context loaders that bind the same scope defintion to different implementations:

public final class SessionScopeContextLoader extends GenericXmlContextLoader {

   protected void customizeContext(final GenericApplicationContext context) {
     final SessionScope testSessionScope = new SessionScope();
     context.getBeanFactory().registerScope("superscope", testSessionScope);
   }
    ...
}

Then you make a corresponding one for singleton (make your own scope with just statics)

Then you just specify the appropriate context loader in the xml startup for each of the two contexts.

krosenvold
Where should I specify the appropriate context loader in WebContext? I don't really get the point about the custom scope, sorry. I found your conversion here http://stackoverflow.com/questions/450557/custom-spring-scopes but it didn't get me the point either...
Frank Szilinski

related questions