java mvc 新趋势——从运行期间类扫描到编译期间

7次阅读

共计 1699 个字符,预计需要花费 5 分钟才能阅读完成。

简介
今天我要讲解的是主角是 Annotation Processor,她不是什么新技术 jdk 1.6 就存在了。Annotation Processor 是 javac 的一个工具,它用来在编译时扫描和处理注解。通过 Annotation Processor 可以获取到注解和被注解对象的相关信息,然后根据注解自动生成 Java 代码,省去了手动编写,提高了编码效率。
案例
大部分 java 开发者每天也在使用她,比较著名的就是 Lombok。
在项目中使用 Lombok 可以减少很多重复代码的书写。比如说 constructor/getter/setter/toString 等方法的编写。如图:

感触最大的就是,添加或更改了 feild 属性,再也不用去生成 get set 了。
spring boot 中最典型的算 spring-boot-configuration-processor 了。他会在代码编译期间将我们的配置数据 spring-configuration-metadata.json 生成到 jar 包中。方便 idea 识别出来,并提供友好的提示。
如图:

spring 5 spring-context-indexer 浅析
生成 spring.components 文件
maven
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-indexer</artifactId>
<version>5.1.4.RELEASE</version>
<scope>optional</scope>
</dependency>

Gradle
annotationProcessor “org.springframework:spring-context-indexer:5.1.4.RELEASE”

项目编译完成时就会就会生成 META-INF/spring.components 文件到 jar 包中。如图:(spring.components 文件)
spring.components 解析和加载

spring-context 中添加了一个 @Indexed 注解。
spring ioc 基础注解 @Component 中组合了 @Indexed 注解,
org.springframework.context.index.CandidateComponentsIndexLoader 则用来加载 spring.components, 标注的这些类。

问题
swagger 目前暂时还有问题,直到现在还没修复,详见 issues:https://github.com/springfox/…
优势

将运行期间的类扫描提前到了编译期间,增加服务启动速度。
避免各种容器类扫描的差异性,提搞兼容性。

链接
Spring 5 – spring-context-indexer:https://github.com/spring-pro…
启发
在 Spring 5 – spring-context-indexer 的启发下,我开发了 mica-auto。编译期间自动生成 Spring boot 的 spring-devtools.properties,扫描 @Configuration,自动生成到 spring.factories 文件,同时将 FeignClient 信息也生成到 spring.factories 中,供 mica 中完成 Feign 自动化配置。
再也不用担心忘了更改 spring.factories 文件而导致服务启动出错。
开源推荐
Spring boot 微服务高效开发 mica 工具集:https://gitee.com/596392912/micaAvue 一款基于 vue 可配置化的神奇框架:https://gitee.com/smallweigit…pig 宇宙最强微服务(架构师必备):https://gitee.com/log4j/pigSpringBlade 完整的线上解决方案(企业开发必备):https://gitee.com/smallc/Spri…IJPay 支付 SDK 让支付触手可及:https://gitee.com/javen205/IJPay

正文完
 0