Injecting using request scope and threads

1.7k Views Asked by At

I have some bussines classes that get injected some dependencies that are provided using servlet request scope.

The problem is that I want to use that bussines classes in some threads that outlive the servlet request. Whats the most transparent way to do that?

4

There are 4 best solutions below

1
On

If you are using Spring (which, by the terms you use to describe your problem, you seem to be using), you can use an AOP scoped-proxy for your request-scoped object, and inject this proxy into the objects that outlive the servlet request. The scoped-proxy will take care of using the right instance everytime you access it.

0
On

Well, I'm not sure if I get your problem. I think there is problem with architecture itself, but however this could help you:

Guice module

bind(Bussines.class).annotatedWith(Names.named("request")).to(Bussines.class).in(RequestScoped.class);
bind(Bussines.class).annotatedWith(Names.named("session")).to(Bussines.class).in(SessionScoped.class);
bind(Bussines.class).annotatedWith(Names.named("application")).to(Bussines.class).asEagerSingleton();

Usage

    @Inject @Named("request")
    private Bussines bussines; //inject a new bussines class every request

    @Inject @Named("session")
    private Bussines bussines; //inject a new bussines class each session
//This is little bit tricky, cuz Bussines is stored in session. In Stage.PRODUCTION are all injection created eagerly and there is no session at injection time. Session binding should be done in lazy way - inject provider and call bussinesProvider.get() when em is needed;

    @Inject @Named("application")
    private Bussines bussines; //inject singleton

Also you can use Private modules to bind different scoped objects to a class. Don't forget to expose it.

0
On

I see 3 options:

  • You could add the information you need to an object that has a larger scope like application or session scope
  • You could persist the information in a file or the database and look it up later
  • You could save the information on the thread or use a thread scope: http://code.google.com/p/google-guice/issues/detail?id=114
0
On

I may not suggest you directly use or inject HttpServletRequest at business bean which is not in request scope . because this will break up app layers. if you want the value from the request or request header, then you can pass value to object to pass to the business layer, because otherwise, it is not secure, and generally, app will apply some security interceptor at that request scope , but if you directly inject to other layer , then it jump over and the interceptor may be skipped... this way also break the encapsulation and obvious is anti-pattern.