注释
@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();
}
}
吉思模块
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创建的实例?
你的引述是正确的:"不可能在不是由 Guice 构造的实例上使用方法拦截。
因此,由于您在 offer 方法中调用new Dummy()
,因此它不起作用。
如果您使用
bind(Dummy.class).asEagerSingleton();
确实如此。