【问题标题】:Guice Method Interceptor Not WorkingGuice 方法拦截器不工作
【发布时间】: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 创建的实例?

【问题讨论】:

    标签: java aop guice


    【解决方案1】:

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

    所以既然你在提供方法中调用new Dummy(),它就不起作用了。

    如果你使用

      bind(Dummy.class).asEagerSingleton();
    

    确实如此。

    【讨论】:

    • 是的,对于您共享的示例,您不需要@Provides,因为 Client 也是注入的依赖项,Guice 会为您做到这一点!此外,对于要成为单例的类,您可以在类声明中添加 @Singleton 注释。
    • 那么我可以使用@Provides 实例化客户端依赖项,因为它不需要方法拦截器吗?
    • 很抱歉,您的问题我不清楚。在Dummy 类中使用的Client 是一个依赖项,因为您已经用@Inject 注释了Dummy 类的构造函数,而Client client 是它的唯一参数。与任何其他依赖项一样,您可以在 guice 模块中为类型 Client 指定绑定,这也可以是 @Provides
    • 这对我来说有点反直觉,当你必须定义 Guice 返回的构造对象时应该使用@Provides,使用 bind 不应该更多地用于模块中的接口类绑定?
    猜你喜欢
    • 2012-02-10
    • 2015-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-11
    • 2012-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多