【发布时间】:2018-04-22 17:05:23
【问题描述】:
注释
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD})
public @interface PublishMetric {
}
拦截器
public class PublishMetricInterceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
System.out.println("invoked");
return methodInvocation.proceed();
}
}
Guice 模块
public class MetricsModule extends AbstractModule {
@Override
protected void configure() {
bindInterceptor(any(), annotatedWith(PublishMetric.class), new PublishMetricInterceptor());
}
@Provides
@Singleton
public Dummy getDummy(Client client) {
return new Dummy(client);
}
}
用法
public class Dummy {
private final Client client;
@Inject
public Dummy(final Client client) {
this.client = client;
}
@PublishMetric
public String something() {
System.out.println("something");
}
}
我不确定为什么这个拦截器不起作用。 Guice AOP Wiki 声明
实例必须由 Guice 通过 @Inject 注释或无参数构造函数创建。不能对非 Guice 构造的实例使用方法拦截。
是否使用@Provides 注解创建新的对象被视为Guice 创建的实例?
【问题讨论】: