【发布时间】:2012-03-18 20:37:20
【问题描述】:
这里有新海报,希望我不要违反任何规则:)
我在 google-guice 中使用 PrivateModule,以便为同一环境提供多个 DataSource。但是我很难让 MethodInterceptor 在私有模块中工作。 下面是一个解释“问题”的简单测试用例。
一个简单的服务类是:
interface Service {
String go();
}
class ServiceImpl implements Service {
@Override @Transactional
public String go() {
return "Test Case...";
}
}
MyModule 类将是:
class MyModule extends AbstractModule {
@Override
protected void configure() {
install(new PrivateModule() {
@Override
protected void configure() {
bind(Service.class).to(ServiceImpl.class);
bindInterceptor(
Matchers.any(),
Matchers.annotatedWith(Transactional.class),
new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation i)
throws Throwable {
System.out.println("Intercepting: "
+ i.getMethod().getName());
return i.proceed();
}
});
expose(Service.class);
}
});
}
}
最后的测试用例:
public class TestCase {
@Inject Service service;
public TestCase() {
Guice.createInjector(new MyModule()).injectMembers(this);
}
public String go() {
return service.go();
}
public static void main(String[] args) {
TestCase t = new TestCase();
System.out.println(t.go());
}
}
你会期望输出是:
Intercepting: go
Test Case...
但是没有发生,没有使用拦截器,只输出了antTest Case...。
如果我绑定/公开ServiceImpl 而不是接口,那么它可以工作。
提前致谢, 问候, LL
【问题讨论】: