我想使用 google guice 使属性在我的应用程序的所有类中可用。我定义了一个加载并绑定属性文件的模块测试属性.
Property1=TEST
Property2=25
包com.test;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
import com.google.inject.AbstractModule;
import com.google.inject.name.Names;
public class TestConfiguration extends AbstractModule {
@Override
protected void configure() {
Properties properties = new Properties();
try {
properties.load(new FileReader("Test.properties"));
Names.bindProperties(binder(), properties);
} catch (FileNotFoundException e) {
System.out.println("The configuration file Test.properties can not be found");
} catch (IOException e) {
System.out.println("I/O Exception during loading configuration");
}
}
}
我正在使用一个主类,在其中创建一个注入器来注入属性。
package com.test;
import com.google.inject.Guice;
import com.google.inject.Injector;
public class Test {
public static void main(String[] args) {
TestConfiguration config = new TestConfiguration();
Injector injector = Guice.createInjector(config);
TestImpl test = injector.getInstance(TestImpl.class);
}
}
package com.test;
import com.google.inject.Inject;
import com.google.inject.name.Named;
public class TestImpl {
private final String property1;
private final Integer property2;
@Inject
public TestImpl(@Named("Property1") String property1, @Named("Property2") Integer property2) {
System.out.println("Hello World");
this.property1 = property1;
this.property2 = property2;
System.out.println(property1);
System.out.println(property2);
}
}
现在我的问题。如果我的 TestImpl 创建其他类,我也需要注入属性,并且这些类也需要注入属性,那么正确的方法是什么?
将注入器传递给所有子类,然后使用injector.getInstance(...) 创建子类?
-
实例化一个新的注入器,例如
TestConfiguration config = new TestConfiguration();
Injector injector = Guice.createInjector(config);
TestImpl test = injector.getInstance(TestImpl.class);
在所有嵌套类中?
- 是否有其他方法可以使这些属性在所有类中可用?
将注入器传递给所有子类,然后使用
Injector.getInstance(...) 创建子类?
不,这样做你就违背了目的依赖注入 http://en.wikipedia.org/wiki/Dependency_injection模式并将所有实现耦合到 Guice。除了通过(现在标准化的)注释之外,您的实现根本不应该与 guice 交互。
实例化一个新的注入器,例如
TestConfiguration config = new TestConfiguration();
Injector injector = Guice.createInjector(config);
TestImpl test = injector.getInstance(TestImpl.class);
在所有嵌套类中?
不,这更糟糕,因为您最终会得到多个注入器,因此多个上下文将阻止正确使用scopes http://code.google.com/p/google-guice/wiki/Scopes.
理想情况下,您应该仅在应用程序引导期间使用注入器。当然,引导它的方式很大程度上取决于应用程序。
是否有其他方法可以使所有属性都可用
课程?
可以按照与 TestImpl 相同的方式注入属性。
如果您希望 TestImpl 使用一个还需要某些属性(或其他服务)的服务,只需让 Guice 将其注入到 TestImpl 即可。 Guice 负责所有实例化/连接。当 Guice 自己无法弄清楚时,您应该只通过使用活页夹告诉 Guice“如何继续”:
public class TestImpl {
private final String property1;
private final Integer property2;
private final IService service;
@Inject
public TestImpl(@Named("Property1") String property1, @Named("Property2") Integer property2, IService service) {
this.property1 = property1;
this.property2 = property2;
this.service= service;
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)