I’m starting to use Google Guice for my daily programming tasks. I needed to pass an existing object to Injector for initializing object graph, so I use method Injector#injectMembers(instance) to do it. But I wasn’t sure if it works so I wrote a unit test, but it didn’t work as I expected. Did I miss something? I use Guice 3
public class Login_Should {
@Test
public void testName() throws Exception {
Login login = new Login();
Injector injector = Guice.createInjector(new LoginModule());
injector.injectMembers(login);
LoginWrapper caller = injector.getInstance(LoginWrapper.class);
assertEquals(login.getName(), caller.getName());
}
}
public class Login {
private int random;
public Login() {
this.random = new Random().nextInt();
}
public String getName() {
return "Mr. A" + random;
}
}
public class LoginWrapper {
private Login login;
@Inject
public LoginWrapper(Login login) {
this.login = login;
}
public String getName() {
return login.getName();
}
}
public class LoginModule extends AbstractModule{
@Override
protected void configure() {
bind(LoginWrapper.class);
}
}
injectMembersinjects a none-Guice created object with its dependencies. What you want to do I think isbind(Login.class).toInstance(login);in your module.