使用Guice时,是否可以获取绑定在模块中的对象?

时间:2016-08-02 01:17:28

标签: guice

public class MyModule extends AbstractModule {

    @Override
    protected void configure() {
        bind(Helper.class).toProvider(HelperProvider.class);
        ServiceInterceptor serviceInterceptor = new ServiceInterceptor(manager);
        bindInterceptor(annotatedWith(With.class), annotatedWith(ServiceName.class), serviceInterceptor);
    }

    @Provides
    @Singleton
    public Manager manager(final Helper helper) {
       Manager manager = new DefaultManager(helper);
       return manager;
    }
}

基本上,我的问题是我需要管理器实例来创建serviceInterceptor实例,我需要在bindInterceptor中使用serviceInterceptor。我对Guice很新,所以我觉得这很简单,我无法找到解决办法......

1 个答案:

答案 0 :(得分:0)

这可以通过请求对象实例的注入来解决。考虑一下我写的这个例子:

public class TestModule2 extends AbstractModule {

    @Override
    protected void configure() {
        bind(Helper.class).in(Singleton.class);
        bind(Manager.class).to(ManagerImpl.class).in(Singleton.class);

        MyInterceptor i = new MyInterceptor();
        requestInjection(i); // intercept the thing

        bindInterceptor(Matchers.any(), Matchers.any(), i);
    }

    public static interface Manager {
        public void talk();
    }

    public static class ManagerImpl implements Manager {

        @Inject
        public ManagerImpl(Helper h) {
        }

        @Override
        public void talk() {
            System.out.println("talking");
        }
    }

    public static class Helper {

    }

    public static class MyInterceptor implements MethodInterceptor {

        @Inject
        private Manager m;

        public MyInterceptor() {
        }

        @Override
        public Object invoke(MethodInvocation invocation) throws Throwable {
            System.out.println("intercept and manager " + m.getClass().getName());
            return invocation.proceed();
        }
    }

    public static void main(String[] args) {
        Injector createInjector = Guice.createInjector(new TestModule2());
        Manager instance = createInjector.getInstance(Manager.class);
        instance.talk();
    }
}

解释:

  1. 我首先以正常方式绑定我的所有实例。这将是Helper和经理。经理可以注入帮助等等。不要忘记注入注释。

  2. 我创建了拦截器方法。现在我需要注入它。 Guice有一种方法:

    MyInterceptor i = new MyInterceptor();
    requestInjection(i); // inject the thing
    
  3. 现在将Manager实例放入拦截器中。

    最后,当我运行上面的代码时,我得到了:

    intercept and manager test.guice.TestModule2$ManagerImpl$$EnhancerByGuice$$e5e270bc
    talking
    

    请注意,拦截器正在打印其消息,然后执行方法调用。

    我希望有所帮助,

    阿图尔