Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guice Method Interceptor Not Working

Tags:

java

aop

guice

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?

like image 282
Vaishal Avatar asked Mar 28 '26 17:03

Vaishal


1 Answers

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.

like image 137
Jan Galinski Avatar answered Mar 31 '26 10:03

Jan Galinski