模块输出的 Guice Names.bindProperties(binder(), properties)?
Guice Names.bindProperties(binder(), properties) on output of a module?
我使用外部服务来提供属性,但希望将这些属性作为 @Named(..) 变量提供。尝试在配置方法中执行此操作失败并显示 npe:
Names.bindProperties(binder(), myPropRetriever.getProperties());
失败是因为 myPropRetriever 在 guice 完成它的工作之前不会出现。我明白为什么这是有道理的——有人知道任何可能解决的时髦黑客吗?在这种情况下会很方便..
感谢 durron597 对相关问题的指导,这让我有足够的时间去弄清楚。答案是使用子注入器对之前的注入器输出采取行动。示例如下:
Injector propInjector = Guice.createInjector(new PropertiesModule());
PropertiesService propService = propInjector.getInstance(PropertiesService.class);
Injector injector = propInjector.createChildInjector(new MyModule(Objects.firstNonNull(propService.getProperties(), new Properties())));
注射器现在是应用其余部分的注射器。
然后在 MyModule 中您可以对创建的对象执行操作:
public class MyModule extends AbstractModule {
private final Properties properties;
public MyModule(Properties properties){
this.properties=properties;
}
@Override
protected void configure() {
// export all the properties as bindings
Names.bindProperties(binder(), properties);
// move on to bindings
// bind(..);
}
}
以防对其他人有帮助..!
我使用外部服务来提供属性,但希望将这些属性作为 @Named(..) 变量提供。尝试在配置方法中执行此操作失败并显示 npe:
Names.bindProperties(binder(), myPropRetriever.getProperties());
失败是因为 myPropRetriever 在 guice 完成它的工作之前不会出现。我明白为什么这是有道理的——有人知道任何可能解决的时髦黑客吗?在这种情况下会很方便..
感谢 durron597 对相关问题的指导,这让我有足够的时间去弄清楚。答案是使用子注入器对之前的注入器输出采取行动。示例如下:
Injector propInjector = Guice.createInjector(new PropertiesModule());
PropertiesService propService = propInjector.getInstance(PropertiesService.class);
Injector injector = propInjector.createChildInjector(new MyModule(Objects.firstNonNull(propService.getProperties(), new Properties())));
注射器现在是应用其余部分的注射器。
然后在 MyModule 中您可以对创建的对象执行操作:
public class MyModule extends AbstractModule {
private final Properties properties;
public MyModule(Properties properties){
this.properties=properties;
}
@Override
protected void configure() {
// export all the properties as bindings
Names.bindProperties(binder(), properties);
// move on to bindings
// bind(..);
}
}
以防对其他人有帮助..!