【发布时间】:2012-04-04 01:54:09
【问题描述】:
我想使用 google guice 使属性在我的应用程序的所有类中都可用。我定义了一个模块,它加载和绑定属性文件 Test.properties。
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);
在所有嵌套类中?
- 是否有其他方法可以使属性在所有类中可用?
【问题讨论】:
-
您是否有理由手动更新它们,而不是使用 guice 将它们注入您的测试类(这将是正常的方式)?
-
你的意思是为什么“TestConfiguration config = new TestConfiguration();”?你能举例说明如何以另一种方式做到这一点吗?
-
@markus: 不,不是
TestConfiguration...new模块是正常的。问题是关于TestImpl创建您还需要注入属性的其他类。通常,您会将那些其他类(或其中的Providers)声明为TestImpl的依赖项,因此Guice 可以创建它们,而不是您在TestImpl中使用new创建它们。 -
我不清楚该怎么做。假设我要创建类 public class TestExtension { @Inject public TestExtension(@Named("Property1") String property1, @Named("Property2") Integer property2) { System.out.println(property1); System.out.println(property2); } } 我如何告诉 guice 创建它?
-
您阅读过Getting Started 指南吗?这将告诉您如何使用 guice 以及如何设置简单的绑定。
标签: java properties guice