繁体   English   中英

Java 注解在方法前后执行代码

[英]Java annotation to execute code before and after method

我正在尝试使用此解决方案(来自这篇文章),但在使用 Quarkus 构建过程中出现错误。

自定义注解:

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

方法拦截器:

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

以及在任何具有注释的方法上绑定拦截器的模块。

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

我得到的错误:

[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

该示例代码需要 Google Guice。 Quarkus 有自己的机制。 https://quarkus.io/guides/cdi在第 14.2 节中包含一些示例。

简而言之:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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