質問

I am new to Guice and have done a lot of reading on this but I have not hand any success with this. I am basically creating a DAO and want to use Guice and the AssistedInjection. Effectively the end goal is create the Injected factory in other classes throughout the application.

Intended use in a actual class that would have the injection of the factory to then get classes from it

public class TestAllModelBootstrap {
   @Inject private DAOFactory factory;
   public TestAllModelBootstrap() {
   }

   @Test
   public void testGettingDAO() {
      Injector injector = Guice.createInjector(new HibernateDAOModule());
      Token oToken = new OperTokenV1();
      AccountingDAO accountingDAO = factory.create(oToken);
   }
}

This is based on Guice-based code of:

public interface DAOFactory {
    public AccountingDAO create(Token oTicket);
}

The concrete class has a constructor annoated

@Inject
public HibernateAccountingDAO(@Assisted Token oTicket) {

    this.oTicket = oTicket;
}

And the actual Module:

@Override
protected void configure() {
    install(new FactoryModuleBuilder()
            .implement(AccountingDAO.class, HibernateAccountingDAO.class)
            .build(DAOFactory.class));

    bind(SessionFactoryInterface.class)
            .toProvider(HibernateSessionProvider.class);
}

Each time I try to run this: java.lang.NullPointerException -> indicating that the:

factory.create(oToken);

has factory as a null. In reading up on the problem I was lead to believe that the injection will not work like I am using it in the "test" class. It needs to be put in an "injected" class itself. But this doesn't work either - if I wrapper the Factory injection in another class and then try to use it, it doesn't work.

Any help would be appreciated...

役に立ちましたか?

解決

TestAllModelBootstrap did not come from an Injector—JUnit created it instead—so Guice hasn't had a chance to inject it yet. Guice can only inject into objects that it creates via getInstance (and those objects' dependencies, recursively), or objects passed into injectMembers, or existing instances as requested using requestInjection.

You can manually get a factory instance:

factory = injector.getInstance(DAOFactory.class);

Or ask Guice to inject your members using injectMembers:

injector.injectMembers(this); // sets the @Inject factory field

Or use a tool like Guiceberry to inject your test cases across your app.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top