Maven compiler插件配置自定义注解处理器与Immutables冲突问题求助
解决方案
问题根源
当你在maven-compiler-plugin的configuration中显式配置<annotationProcessors>列表时,Maven会关闭类路径自动注解处理器扫描,仅加载你指定的处理器,所以类路径下的Immutables处理器不会被触发,从而导致编译报错。
方案1:显式声明所有注解处理器
直接将Immutables和其他需要用到的第三方注解处理器全类名,补充到<annotationProcessors>列表中即可,修改后的配置示例如下:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> <generatedSourcesDirectory>${project.build.directory}/generated-sources/</generatedSourcesDirectory> <annotationProcessors> <!-- 你的自定义注解处理器 --> <annotationProcessor>org.smarttechie.TraceAnnotationProcessor</annotationProcessor> <!-- 新增Immutables注解处理器 --> <annotationProcessor>org.immutables.processor.ProxyProcessor</annotationProcessor> <!-- 其他第三方注解处理器也按这个格式依次添加即可 --> </annotationProcessors> </configuration> </plugin>
使用本方案需要确保你的自定义注解处理器、Immutables依赖都已经在项目的普通依赖列表中正确引入。
方案2:使用annotationProcessorPaths统一管理(更推荐)
如果不想逐个维护注解处理器的全类名,可以使用<annotationProcessorPaths>标签统一管理所有处理器依赖,Maven会自动扫描路径下所有的注解处理器实现,不需要单独声明全类名,同时处理器依赖不会混入项目的业务编译类路径,更干净规范,配置示例如下:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> <generatedSourcesDirectory>${project.build.directory}/generated-sources/</generatedSourcesDirectory> <annotationProcessorPaths> <!-- 你的自定义注解处理器依赖,替换成对应坐标即可 --> <path> <groupId>org.smarttechie</groupId> <artifactId>trace-annotation-processor</artifactId> <version>1.0.0</version> </path> <!-- Immutables注解处理器依赖,替换成你正在使用的版本号 --> <path> <groupId>org.immutables</groupId> <artifactId>value</artifactId> <version>2.9.0</version> </path> <!-- 其他第三方注解处理器也按这个格式添加即可 --> </annotationProcessorPaths> </configuration> </plugin>
使用本方案不需要在项目的普通
<dependencies>列表中引入注解处理器相关依赖,避免冗余。
注意事项
- 如果你使用的是IntelliJ IDEA等IDE,修改配置后需要重新导入Maven项目,并且在设置的「注解处理器」选项中开启注解处理功能,避免IDE编译时不识别生成的类。
- JDK 9及以上版本如果开启了模块化,需要在module-info.java中通过
provides javax.annotation.processing.Processor with 你的处理器全类名声明自定义处理器,或者添加对应的JVM启动参数。
内容的提问来源于stack exchange,提问作者SmartTechie
相关产品推荐
相关产品推荐

