frjaeger220 / google-guice

Automatically exported from code.google.com/p/google-guice
Apache License 2.0
0 stars 0 forks source link

Inject a session scoped instance with specified name (session attribute name) #97

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
Maybe just I don't know it, I can't find a way to inject a session scoped
instance with specified name (session attribute name). Thus I can't use the
instance on my jsp page, for example, sessionScope.<myAttributName>.value.
Or that's not the way the thing should go?

Original issue reported on code.google.com by kevin.wa...@gmail.com on 28 Apr 2007 at 5:49

GoogleCodeExporter commented 9 years ago
The session scoped instance is stored under the name obtained by converting the 
"Key"
to a string.
For an injected field of type "com.example.Service" and no annotation, this 
will look
something like "Key[type=com.example.Service, annotation=[none]]"
Within your JSP page you can then use:
<c:set var="serivceRef" value="${sessionScope['Key[type=com.example.Service,
annotation=[none]]']}"/> 

Of course, it would be nice to check if the key includes the
'com.google.inject.name.Named' annotation, and then just use the name as the 
session
attribute name.

Otherwise you can always create your own custom scope (based on
com.google.inject.servlet.ServletScopes) to do this.

Original comment by tonyand...@gmail.com on 14 Jan 2008 at 12:38

GoogleCodeExporter commented 9 years ago
Usually you should use @SessionScoped so I don't need to interact with the 
HttpSession directly. To do so, 
create a binding like this one in your module:
        bind(MyService.class).toProvider(new Provider<MyService>() {
          @Inject HttpSession session;
          public MyService get() {
            return (MyService) session.getAttribute("myService");
          }
        });

Guice's built-in support is preferred since it provides more type safety (no 
casts!).

Original comment by limpbizkit on 31 May 2008 at 7:16