我需要将参数注入(inject)库中对象 (Template
) 的构造函数,这意味着我无法注释该对象。构造函数参数从属性文件加载:
foo=value1
bar=value2
public class MyModule extends AbstractModule {
private Properties properties;
public void configure() {
Names.bindProperties(binder(), getProperties());
bind(Template.class);
}
public Properties getProperties() {
if (properties == null) {
loadProperties();
}
return properties;
}
private loadProperties() {
...
}
....
}
如果我有模板的源代码,我会注释它的构造函数:
public class Template {
@Inject
public Template(@Named("foo") String foo, @Named("bar") String bar) {
....
}
....
}
如果没有注释源以从属性文件注入(inject)参数的能力,可以做什么? 谢谢!
最佳答案
在您的模块中使用 Provider 方法:
@Provides
public Template newTemplate(@Named("foo") String foo, @Named("bar") String bar) {
return new Template(foo, bar);
}
注意:正如 Nathan 上面所说,这种方法不允许在模板实例上使用 guice aop,因为它不是由 guice 创建的。如果这很重要,您将不得不使用子类。
关于java - 使用 Guice 使用属性连接库对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34418460/