2011-03-23 20 views
2

我想结合我的模块configure()方法MethodInterceptor,像这样:我可以在Guice的Module.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()); 
    } 
} 

有没有办法让transactionInterceptor与吉斯的帮助,或者我需要创建所需的所有对象我的拦截器手动?

回答

6

这涵盖在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))); 
    } 
} 
相关问题