Java 我可以在Guice';中使用已绑定的实例吗;s Module.configure()?
我想在模块的Java 我可以在Guice';中使用已绑定的实例吗;s Module.configure()?,java,dependency-injection,guice,Java,Dependency Injection,Guice,我想在模块的configure()方法中绑定一个MethodInterceptor,如下所示: public class DataModule implements Module { @Override public void configure(Binder binder) { MethodInterceptor transactionInterceptor = ...; binder.bindInterceptor(Matchers.any(
configure()
方法中绑定一个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是如何编写的。具体来说,是及其模块。这在中介绍。从该文件中:
为了在AOP MethodInterceptor中注入依赖项,请在标准bindInterceptor()调用的同时使用requestInjection()
另一个选项是使用Binder.getProvider并在拦截器的构造函数中传递依赖项
public class NotOnWeekendsModule extends AbstractModule {
protected void configure() {
bindInterceptor(any(),
annotatedWith(NotOnWeekends.class),
new WeekendBlocker(getProvider(Calendar.class)));
}
}
public class NotOnWeekendsModule extends AbstractModule {
protected void configure() {
bindInterceptor(any(),
annotatedWith(NotOnWeekends.class),
new WeekendBlocker(getProvider(Calendar.class)));
}
}