我想在模块的MethodInterceptor方法中绑定configure(),如下所示:

public class DataModule implements Module {

    @Override
    public void configure(Binder binder) {
        MethodInterceptor transactionInterceptor = ...;
        binder.bindInterceptor(Matchers.any(), Matchers.annotatedWith(Transactional.class), null);
    }

    @Provides
    public DataSource dataSource() {
        JdbcDataSource dataSource = new JdbcDataSource();
        dataSource.setURL("jdbc:h2:test");
        return dataSource;
    }

    @Provides
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Provides
    public TransactionInterceptor transactionInterceptor(PlatformTransactionManager transactionManager) {
        return new TransactionInterceptor(transactionManager, new AnnotationTransactionAttributeSource());
    }
}


有没有办法在Guice的帮助下获取transactionInterceptor,还是我需要手动创建拦截器所需的所有对象?

最佳答案

Guice FAQ中对此进行了介绍。从该文档中:

为了将依赖项注入AOP MethodInterceptor中,请在标准bindInterceptor()调用旁边使用requestInjection()。

public class NotOnWeekendsModule extends AbstractModule {
  protected void configure() {
    MethodInterceptor interceptor = new WeekendBlocker();
    requestInjection(interceptor);
    bindInterceptor(any(), annotatedWith(NotOnWeekends.class), interceptor);
  }
}


另一个选择是使用Binder.getProvider并在拦截器的构造函数中传递依赖项。

public class NotOnWeekendsModule extends AbstractModule {
  protected void configure() {
    bindInterceptor(any(),
                annotatedWith(NotOnWeekends.class),
                new WeekendBlocker(getProvider(Calendar.class)));
  }
}

关于java - 我可以在Guice的Module.configure()中使用已经绑定(bind)的实例吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5408105/

10-11 20:34