Guice 方法拦截器不工作

Vai*_*hal 3 java aop guice

注解

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD})
public @interface PublishMetric {
}
Run Code Online (Sandbox Code Playgroud)

拦截器

public class PublishMetricInterceptor implements MethodInterceptor {
  @Override
  public Object invoke(MethodInvocation methodInvocation) throws Throwable {
    System.out.println("invoked");
    return methodInvocation.proceed();
  }
}
Run Code Online (Sandbox Code Playgroud)

指南模块

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

用法

public class Dummy {
  private final Client client;

  @Inject
  public Dummy(final Client client) {
    this.client = client;
  }

  @PublishMetric
  public String something() {
    System.out.println("something");
  }
}
Run Code Online (Sandbox Code Playgroud)

我不确定为什么这个拦截器不起作用。Guice AOP Wiki 指出

实例必须由 Guice 通过 @Inject 注释或无参数构造函数创建。 不可能对不是由 Guice 构造的实例使用方法拦截。

使用@Provides注解创建新对象是否被视为Guice创建的实例?

Jan*_*ski 8

您的引用是正确的:“不可能对不是由 Guice 构造的实例使用方法拦截。”

因此,由于您正在调用new Dummy()提供方法,因此它将不起作用。

如果你使用

  bind(Dummy.class).asEagerSingleton();
Run Code Online (Sandbox Code Playgroud)

确实如此。