Guice 方法拦截器不工作

Guice Method Interceptor Not Working

注释

@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 指出

Instances must be created by Guice by an @Inject-annotated or no-argument constructor It is not possible to use method interception on instances that aren't constructed by Guice.

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

你的话是真的:"It is not possible to use method interception on instances that aren't constructed by Guice."

因此,由于您在 provides 方法中调用 new Dummy(),因此它不会起作用。

如果你使用

  bind(Dummy.class).asEagerSingleton();

确实如此。