java - tomcat 未调用自定义注释处理器

标签 java tomcat annotations annotation-processing annotation-processor

tomcat 未调用自定义注释处理器。以下是我正在使用的注释处理器代码:

@SuppressWarnings("restriction")
@SupportedAnnotationTypes("io.strati.rs.cxf2.bindings.MyAnnotation")
@SupportedSourceVersion( SourceVersion.RELEASE_8 )
public class SimpleAnnotationProcessor extends AbstractProcessor {

    public static List<String> str = new ArrayList<>();

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {

        System.out.println("Into annotation processor ... 2");

        for ( Element element : roundEnv.getElementsAnnotatedWith(MyAnnotation.class)) {
            System.out.println("Method name is:"+element.getSimpleName());
            str.add(element.getSimpleName().toString());
        }   
        return false;
    }
}

这存储了所有具有自定义注释的方法的方法名称。这是注释类的样子:

@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(value = RetentionPolicy.RUNTIME)
public @interface MyAnnotation {

}

我正在尝试访问 tomcat 应用程序中的列表,如下所示:

@GET
@Path("/dummy")
@MyAnnotation
@Produces({APPLICATION_JSON, APPLICATION_XML, TEXT_XML})
public void print(){
   System.out.println("List is:"+SimpleAnnotationProcessor.str);
}

即使该方法具有注释,该列表也被打印为空。我已经在 maven 编译器插件中指定了注释,并在 META-INF/services/javax.annotation.processing.Processor 中指定了它。有人能告诉我注释处理器未被调用的可能原因是什么吗?

最佳答案

我怀疑 Tomcat 与它有任何关系。注释处理发生在编译时,通常用于生成或修改代码。注释处理器可以看作是编译器插件。

https://www.javacodegeeks.com/2015/09/java-annotation-processors.html

Following the retention policy, the annotation is going to be retained by Java compiler in the class file during the compilation phase however it will not be (and should not be) available at runtime.

注释处理器可能实际上将 print() 方法名称添加到列表中(检查构建输出),但这同样只在编译代码时发生。

运行时部署的 web 服务永远不会看到处理器在编译时填充的列表,那是完全不同的环境。

关于java - tomcat 未调用自定义注释处理器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43994114/

相关文章:

java - 在 Micronaut,我如何获取对象数组作为配置属性

java - Maven:BDD 构建并将 "plug-in" Artifact 复制到程序文件夹,然后运行程序进行测试?

java - 在 Custom BottomSheetDialog Android 中添加菜单

java - 爬取文件系统和索引的最佳方式

c# - 如何将整数参数的字符串表示形式返回为基数 16 的无符号整数

java - 使用 spring 下载上传的文件。 Tomcat 服务器随机卡住

tomcat - 解释 tomcat 线程转储和诊断死锁

MySQL 连接超时问题 - 使用 Hibernate 和 ORM 的 Tomcat 上的 Grails 应用程序

jsp - 你能把一个 WebFilter 打包成一个库吗

java - 为什么 @Documented 注解有运行时保留?