繁体   English   中英

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();
  }
}

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-annotated或无参数构造函数创建。不可能对非Guice构造的实例使用方法拦截。

使用@Provides注释来创建新的Object是否被认为是由Guice创建的实例?

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

因此,由于您在提供方法中调用了new Dummy() ,因此无法正常工作。

如果你使用

  bind(Dummy.class).asEagerSingleton();

它确实。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM