Guice: Using parameter in Module (JndiIntegration)

假如想象 提交于 2020-03-05 09:58:26

问题


I've a module like this

public class JNDITransactionModule implements Module{

    @Override
    public void configure(Binder binder) {
        binder.bind(TransactionManager.class)
              .toProvider(
                   JndiIntegration.fromJndi(
                      TransactionManager.class, 
                      "URI TO TRANSACTION MANAGER"))
              .in(Scopes.SINGLETON);
    }
}

Well, I think my question is easy, but... how can I parametrize the "URI TO TRANSACTION MANAGER" value??

I mean, something like this

public class JNDITransactionModule implements Module{

    @Override
    public void configure(Binder binder) {
           Properties props = getProperties("transaction.properties");
           Names.bindProperties(binder, props);

        binder.install(new TransactionModule());
        binder.bind(TransactionManager.class)
              .toProvider(
                   JndiIntegration.fromJndi(
                      TransactionManager.class, 
                      "get @Named('transaction.jndi-uri')"))
              .in(Scopes.SINGLETON);
    }
}

and a configuration file called transaction.properties which contains this

  transaction.jndi-uri = URI TO TRANSACTION MANAGER

Thanks!!!


回答1:


You should be able to use a separate provider or a @Provides method. The following should work:

@Provides
@Singleton
TransactionManager provideTransactionManager(@Named("transaction.jndi-uri") String uri) {
    return JndiIntegration.fromJndi(TransactionManager.class, uri).get();
}


来源:https://stackoverflow.com/questions/8991654/guice-using-parameter-in-module-jndiintegration

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!