我想使用 Guice 来生成实例(实际上是模块/依赖项注入(inject)上下文的单例/单个实例),但有一些托管实例被包装在代理中。
这背后的想法是围绕处理“一次一个”资源的几个项目添加一个同步层。我想出的唯一解决方案是创建两个注入(inject)器。
给出下面的代码,
public class ApplicationContext {
private Injector injector;
public <T> T get(Class<? extends T> cls) {
return injector.getInstance(cls);
}
public ApplicationContext() {
injector = Guice.createInjector(new Module() {
binder.bind(InterfaceOne.class).to(ImplementationOne.class);
binder.bind(InterfaceTwo.class).to(ImplementationTwo.class);
binder.bind(InterfaceThree.class).to(ImplementationThree.class);
});
}
}
其中 ImplementationThree
依赖于 InterfaceTwo
,而 ImplementationTwo
又依赖于 InterfaceOne
。
我现在想要的是,在 ImplementationTwo
实例化之后,我想在将其注入(inject) ImplementationThree
之前将其包装在 Proxy 中。所以:
- 我想使用 Guice 将
ImplementationOne
注入(inject)到ImplementationTwo
- 在
ImplementationTwo
被注入(inject)到ImplementationThree
之前,我想包装它。
我希望看到的是一个 Guice 拦截器,它在依赖项的实例化和注入(inject)之后但在移交给注入(inject)器上下文之前被调用。
我可以为 ImplementationTwo
使用 Provider
,但我不知道如何从 Guice 获取 InterfaceOne
的实例。
最佳答案
Provider 方法也可以使用注入(inject)。尝试
@Inject @Provides
public InterfaceTwo provideInterfaceTwo(InterfaceOne i){
return InterfaceTwoImplementation
}
关于java - 我如何包装 Guice 生成的实例,而不是自己创建它们,而是让 Guice 根据需要注入(inject)依赖项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16892854/