JDK6提供了一个可以在编译阶断对代码进行额外补充操作的一个功能
该功能有以下几个步骤: 首先需要继承javax.annotation.processing.AbstractProcesso
r类。
@SupportedAnnotationTypes({"*"})
public class MyProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
System.out.println("start process");
annotations.forEach(s->{
System.out.println(s);
Set<? extends Element> set = roundEnv.getElementsAnnotatedWith(s);
set.forEach(System.out::println);
});
return true;
}
@Override
public Set<String> getSupportedAnnotationTypes() {
return super.getSupportedAnnotationTypes();
}
}
然后在class下添加META-INF/services目录,里面添加一个javax.annotation.processing.Processor
文件,类容为上面的实现类: com.github.liuax.mybatis.batch.autoconfigure.MyProcessor
注意编译时需要传参:<compilerArgument>-proc:none</compilerArgument>。理由:是因为编译该工程时,该处理类还未编译。 新建一个工程,依赖上面打包好的JAR包。运行编译可以看到效果:
[INFO] Compiling 3 source files to Z:\ideaProject\mybatis-batch-parent\mybatis-batch-starter\target\classes
start process
javax.xml.ws.ServiceMode
test.Test2
javax.annotation.Generated
test.Test1
test.Test3
start process
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
再来看看spring-boot是怎么生成元素据提示信息的
需要依赖一个JAR包,该JAR包含一个继承javax.annotation.processing.AbstractProcesso
的实现类。
<!-- @ConfigurationProperties annotation processing (metadata for IDEs) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>2.0.1.RELEASE</version>
<optional>true</optional>
</dependency>
打开原码结构看一下: