简体   繁体   中英

Java annotation to execute code before and after method

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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