I'm currently trying to use Google Guice-3.0 in a small application.
When running this app, the user is prompted to input his name and his password. Since this information is not known until runtime, I use AssistedInject
to implement my User
instantiation.
This is where my UserFactory
comes in. It provides a User
with the method
public User create(@Assisted("Username") String username,
@Assisted("Password") String password);
The User
class is initiated once at the start of the program (after the user input) via
User user = getInjector().getInstance(UserFactory.class).create(username, password);
and I want to use this instance over the lifetime of the application. I have already set the scope to @Singleton
.
The problem is, however, I only get errors. Guice is complaining that I haven't passed any variables when calling
User user = getInjector().getInstance( User.class );
and if I add a bind( User.class );
into the configure
method, an error occurs that there was no declaration to the annotation @Assisted
(since you can put annotations in front of parameters to uniquely identify them - Guice probably thinks it's one of them and demands a dependency to be set (like
bind( String.class ).annotatedWith( Assisted.class ).toInstance( username );
but this is not a thing that would work (maybe it would via static references but then why use Guice?
Here is an example that you can compile. The commented code causes the error. Especially the last 2 lines are pretty irritating to me.
public class KSKB {
@Singleton
public static class User {
public final String name;
@Inject
public User(@Assisted("Username") String username) {
this.name = username;
}
public static interface Factory {
public User create(@Assisted("Username") String username);
}
}
public static void main(String... args) {
Injector injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
install(new FactoryModuleBuilder().build(User.Factory.class));
// bind( User.class );
}
});
User user = injector.getInstance(User.Factory.class).create("Guice");
System.out.println(user.name);
// user = injector.getInstance( User.class ); // doesn't work - throws Exception!!
// System.out.println( user.name );
}
}