Annotation
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD})
public @interface PublishMetric {
}
Interceptor
public class PublishMetricInterceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
System.out.println("invoked");
return methodInvocation.proceed();
}
}
Guice Module
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);
}
}
Usage
public class Dummy {
private final Client client;
@Inject
public Dummy(final Client client) {
this.client = client;
}
@PublishMetric
public String something() {
System.out.println("something");
}
}
I am not sure why this interceptor is not working. Guice AOP Wiki states that
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.
Does using @Provides annotation to create new Object considered an instance created by Guice?
Your quote ist true: "It is not possible to use method interception on instances that aren't constructed by Guice."
So since you are calling new Dummy() in the provides method, it won't work.
If you use
bind(Dummy.class).asEagerSingleton();
it does.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With