java - 我可以在 Guice 的 Module.configure() 中使用已经绑定(bind)的实例吗?

标签 java dependency-injection guice

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

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 中注入(inject)依赖项,请使用 requestInjection() 以及标准的 bindInterceptor() 调用。

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/

相关文章:

java - 用java制作Jhipster REST客户端

javascript - 如果依赖项留空,应用程序将无法工作;如果依赖项完全删除,应用程序将工作

c# - 使用 'where' 谓词从 Windsor CaSTLe 中的 Assembly 注册类型

java - 使用 Java 绘制旋转的 ImageIcon

java - 覆盖 gwt 中包含的表单的处理程序

java - 如何从静态内部类构造函数创建 Spring bean?

java - 什么时候安装 Guice 模块?

Guice annotatedWith 用于与泛型的接口(interface)

java - 使用 GUICE 注入(inject) HttpClient 以在 Java 中获取模拟响应

java - 我有多个布局文件,但应用程序只能识别 1 个?