我如何包装Guice生成的实例,而不是自己创建它们但是根据需要让Guice注入依赖项?

时间:2013-06-03 08:38:05

标签: java guice

我想使用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之前将其包装在代理中。所以:

  • 我想使用Guice将ImplementationOne注入ImplementationTwo
  • ImplementationTwo注入ImplementationThree之前,我想将其包裹起来。

我希望看到的是Guice拦截器,它是在实例化和注入依赖项之后调用的,但在它被移交给注入器上下文之前。

我可以使用Provider ImplementationTwo,但后来我不知道如何从Guice获取InterfaceOne的实例。

2 个答案:

答案 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。