I am new to the the heady world of Guice and have been scratching my head
over this example too. Although binding an named string annotation works
its introduces the chance of typing the named value. *Is there a "proper"
way to inject values passed to a servlet from a client. *
I am only playing around at the moment but made a class to carry the
members to inject:
class User
{
private String username;
.
.
.
}
Then bound it like this in my ServletModule:
bind(User.class).in(ServletScopes.REQUEST);
In the filter I inject it like this:
User user = new User();
user.setUsername(httpRequest.getParameter("username"));
httpRequest.setAttribute(Key.get(User.class).toString(), user);
chain.doFilter(request, response);
Then in another class I consume it like this:
public class DummyListService implements ListService
{
final Provider<User> userProvider;
@Inject
public DummyListService(Provider<User> userProvider)
{
this.userProvider = userProvider;
}
.
.
.
}
Haemish
On Thursday, June 16, 2011 12:11:05 PM UTC-4, atoy40 wrote:
>
> Mmmhhhh .... while waiting to be moderated, i tested some stuffs.
> One is working !
> I added this binding to my guice module :
>
> bind(Key.get(String.class,
> Names.named("username"))).to(String.class).in(RequestScoped.class);
>
> but i don't know if it's the good way to do it ?
>
> Anthony.
>
> On Jun 16, 4:59 pm, atoy40 <[email protected]> wrote:
> > Hello,
> >
> > i'm trying to follow the example athttp://
> code.google.com/p/google-guice/wiki/ServletModule
> > named "Using RequestScope".
> > I need to inject a username (a string) classes of my webapps.
> >
> > So a added a servlet filter doing something like :
> > ---8<---
> > httpRequest.setAttribute(Key.get(String.class,
> > Names.named("username")).toString(), my_username));
> > ---8<---
> > and i added the filter mapping in my guice ServletModule
> >
> > Then in a class requesting the username, an injected it as :
> > ---8<---
> > private final Provider<String> username;
> >
> > @Inject
> > public MyUserService(@Named("username") Provider<String> username) {
> > this.username = username}
> >
> > ---8<---
> >
> > but when the MyUserService class is instancied by guice, i get an
> > exception :
> > No implementation for java.lang.String annotated with
> > @com.google.inject.name.Named(value=username) was bound.
> > while locating com.google.inject.Provider<java.lang.String>
> > annotated with @com.google.inject.name.Named(value=username)
> >
> > Any idea on how to inject the "Key" added to servlet attribute ?
> >
> > Thanks
> > Anthony.
--
You received this message because you are subscribed to the Google Groups
"google-guice" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/google-guice?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.