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/