gpt4 book ai didi

java - Guice 方法拦截器不工作

转载 作者:行者123 更新时间:2023-11-29 04:20:02 25 4
gpt4 key购买 nike

注释

@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创建的实例?

最佳答案

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

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

如果你使用

  bind(Dummy.class).asEagerSingleton();

确实如此。

关于java - Guice 方法拦截器不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49956829/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com