所以基本上,我有一种情况,我想将原始类型注入一个类(即一个字符串和一个整数)。您可以将应用程序的 URL 和端口号视为示例输入。我有三个组件:
现在说我有一堂课,它确实接受了这些参数:
public class PrimitiveParamsDIExample {
private String a;
private Integer b;
public PrimitiveParamsDIExample(String a, Integer b) {
this.a = a;
this.b = b;
}
}
所以我的问题很简单。我如何注入a
和b
上课PrimitiveParamsDIExample
?
一般来说,这也是在询问如何注入在运行时决定的参数。如果我在上面有 a 和 b,从 STDIN 或输入文件中读取,它们显然会因运行而不同。
更何况,我如何在 HK2 框架内完成上述工作?
编辑[02/23/15]:@jwells131313,我尝试了您的想法,但出现以下错误(此错误用于 String 参数;类似的错误用于 int):
org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at Injectee(requiredType=String,parent=PrimitiveParamsDIExample,qualifiers
我完全按照您在答案中所做的设置课程。我还覆盖了toString()
打印变量a
和b
in的方法PrimitiveParamsDIExample
。然后,我在我的 Hk2Module 类中添加了以下内容:
public class Hk2Module extends AbstractBinder {
private Properties properties;
public Hk2Module(Properties properties){
this.properties = properties;
}
@Override
protected void configure() {
bindFactory(StringAFactory.class).to(String.class).in(RequestScoped.class);
bindFactory(IntegerBFactory.class).to(Integer.class).in(RequestScoped.class);
bind(PrimitiveParamsDIExample.class).to(PrimitiveParamsDIExample.class).in(Singleton.class);
}
}
所以现在,我创建了一个测试类,如下所示:
@RunWith(JUnit4.class)
public class TestPrimitiveParamsDIExample extends Hk2Setup {
private PrimitiveParamsDIExample example;
@Before
public void setup() throws IOException {
super.setupHk2();
//example = new PrimitiveParamsDIExample();
example = serviceLocator.getService(PrimitiveParamsDIExample.class);
}
@Test
public void testPrimitiveParamsDI() {
System.out.println(example.toString());
}
}
其中,Hk2Setup 如下:
public class Hk2Setup extends TestCase{
// the name of the resource containing the default configuration properties
private static final String DEFAULT_PROPERTIES = "defaults.properties";
protected Properties config = null;
protected ServiceLocator serviceLocator;
public void setupHk2() throws IOException{
config = new Properties();
Reader defaults = Resources.asCharSource(Resources.getResource(DEFAULT_PROPERTIES), Charsets.UTF_8).openBufferedStream();
load(config, defaults);
ApplicationHandler handler = new ApplicationHandler(new MyMainApplication(config));
final ServiceLocator locator = handler.getServiceLocator();
serviceLocator = locator;
}
private static void load(Properties p, Reader r) throws IOException {
try {
p.load(r);
} finally {
Closeables.close(r, false);
}
}
}
所以在某个地方,我的接线搞砸了,我得到了一个 UnsatisfiedDependencyException。我没有正确连接什么?
谢谢!