Reputation: 11
I am new to guice DI Framework In Spring we can access the session scope variable using el
sessionScope['scopedTarget.sessionService'].loggedUser
But how can I do this in guice?
Upvotes: 0
Views: 269
Reputation: 95634
If you choose to use Guice's Servlet extension, you should be able to bind an HttpSession or Provider<HttpSession> automatically.
In your class, you would put something like this:
private final MyDependency dependency;
private final Provider<HttpSession> sessionProvider;
@Inject
public MyClass(MyDependency dependency, Provider<HttpSession> sessionProvider) {
this.dependency = dependency;
this.sessionProvider = sessionProvider;
}
void callMyService() {
HttpSession session = sessionProvider.get();
String myValue = (String) session.get("value");
// ...
}
Providers are built-in interfaces that let you get fresh instances from the injector. If class Foo is bound, you can always inject Provider<Foo> without any additional work. Here, injecting a Provider is a good idea, because the class you're writing may live longer than any given session.
Upvotes: 1