我想使用Guice来生成实例(实际上是模块/依赖注入上下文的单例/单实例),但是有些托管实例被包装在代理中。
这背后的想法是围绕处理“一次一个”资源的几个项目添加同步层。我提出的唯一解决方案是创建两个注射器。
鉴于以下代码,
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
之后,我想在将它注入ImplementationThree
之前将其包装在代理中。所以:
ImplementationOne
注入ImplementationTwo
ImplementationTwo
注入ImplementationThree
之前,我想将其包裹起来。我希望看到的是Guice拦截器,它是在实例化和注入依赖项之后调用的,但在它被移交给注入器上下文之前。
我可以使用Provider
ImplementationTwo
,但后来我不知道如何从Guice获取InterfaceOne
的实例。
答案 0 :(得分:3)
Provider方法也可以使用注入。尝试
@Inject @Provides
public InterfaceTwo provideInterfaceTwo(InterfaceOne i){
return InterfaceTwoImplementation
}
答案 1 :(得分:0)
为什么不使用普通的Guice AOP支持?像
这样的东西@SynchronizedAccess
public void foo(...){
...
}
通过这种方式你可以看到代码中有更多的东西。
如果你绝对想要在代理中包装东西:
如果你只有几个代理课程,那么@acerberus建议就可以了。
要自动化,您可以#afterInjection使用Custom Injections的一部分,并使用反射将字段重新分配给您的代理。
我觉得使用锁定编程有点陈旧,而我们有akka这样的东西,但是YMMV。