Home > Mobile >  Java annotation to execute code before and after method
Java annotation to execute code before and after method

Time:12-31

I am trying to use this solution (from this post), but I am getting an error during the build process with Quarkus.

Custom annotation:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface WaitCursor {}

The method interceptor:

public class WaitCursorInterceptor implements MethodInterceptor {
    public Object invoke(MethodInvocation invocation) throws Throwable {
        // show the cursor
        MainUI.getInstance().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        // execute the method annotated with `@WaitCursor`
        Object result = invocation.proceed();
        // hide the waiting cursor
        MainUI.getInstance().setCursor(Cursor.getDefaultCursor());
        return result;
    }
}

And the module to bind the interceptor on any method having the annotation.

public class WaitCursorModule extends AbstractModule {
    protected void configure() {
        bindInterceptor(Matchers.any(), Matchers.annotatedWith(WaitCursor.class), new WaitCursorInterceptor());
    }
}

The error I am getting:

[ERROR] Failed to execute goal io.quarkus.platform:quarkus-maven-plugin:2.15.1.Final:dev (default-cli) on project projectName: Unable to execute mojo: Compilation failure
[ERROR] /git/projectName/api/src/main/java/com/packageName/shared/modules/WaitCursorModule.java:[25,9] cannot find symbol
[ERROR]   symbol:   method bindInterceptor(com.google.inject.matcher.Matcher<java.lang.Object>,com.google.inject.matcher.Matcher<java.lang.reflect.AnnotatedElement>,com.packageName.shared.modules.WaitCursorModule)
[ERROR]   location: class com.packageName.shared.modules.WaitCursorModule

CodePudding user response:

That example code requires Google Guice. Quarkus comes with its own mechanism. https://quarkus.io/guides/cdi contains some examples, in section 14.2.

In short:

@InterceptorBinding // added
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD }) // TYPE added
@Inherited // added
@interface WaitCursor {}
@WaitCursor
@Interceptor 
public class WaitCursorInterceptor {

    @AroundInvoke 
    public Object invoke(InvocationContext invocation) throws Throwable {
        // show the cursor
        MainUI.getInstance().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        // execute the method annotated with `@WaitCursor`
        Object result = invocation.proceed();
        // hide the waiting cursor
        MainUI.getInstance().setCursor(Cursor.getDefaultCursor());
        return result;
    }
}
  • Related