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

简介

今天我要讲解的是主角是 Annotation Processor,她不是什么新技术 jdk 1.6 就存在了。 Annotation Processor是javac的一个工具,它用来在编译时扫描和处理注解。经过Annotation Processor能够获取到注解和被注解对象的相关信息,而后根据注解自动生成Java代码,省去了手动编写,提升了编码效率。vue

案例

大部分java 开发者天天也在使用她,比较著名的就是 Lombok。java

在项目中使用Lombok能够减小不少重复代码的书写。好比说constructor/getter/setter/toString等方法的编写。 如图:git

3ec1649b0e05292f2e4561181af713a109e.jpg

感触最大的就是,添加或更改了 feild 属性,不再用去生成 get set 了。github

spring boot 中最典型的算 spring-boot-configuration-processor 了。他会在代码编译期间将咱们的配置数据 spring-configuration-metadata.json 生成到 jar 包中。方便 idea 识别出来,并提供友好的提示。spring

如图: json

05a4a585145ed2535171a6a40255da51a5b.jpg

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文件)maven

spring.components 解析和加载

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

问题

swagger 目前暂时还有问题,直到如今还没修复,详见 issues:https://github.com/springfox/...ide

优点

  1. 将运行期间的类扫描提早到了编译期间,增长服务启动速度。
  2. 避免各类容器类扫描的差别性,提搞兼容性。

连接

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/mica
Avue 一款基于vue可配置化的神奇框架:https://gitee.com/smallweigit...
pig 宇宙最强微服务(架构师必备):https://gitee.com/log4j/pig
SpringBlade 完整的线上解决方案(企业开发必备):https://gitee.com/smallc/Spri...
IJPay 支付SDK让支付触手可及:https://gitee.com/javen205/IJPay

相关文章
相关标签/搜索