引
Spring Framework 5.0作為 Spring Boot 2.0 的底層核心框架,就目前已經發布的版本來看,相對於 Spring Framework 4.x 而言,注解驅動的性能提升不是那么明顯。然而隨着 Spring Framework 注解驅動能能力逐漸受到開發人員的關注,尤其在 Spring Boot 應用場景中,大量使用注解 @CompoentScan 掃描指定的 package,當掃描的 package 所包含的類越多時,Spring 模式注解解析的耗時就越長。對於這個問題,Spring Framework 5.0 版本引入的注解 @Indexed,為 Spring 模式注解添加索引,以提升應用啟動性能。
舉個栗子:
@Indexed @Configuration public class WebMvcConfig implements WebMvcConfigurer {}
但是,注解 @Indexed 不能孤立地存在,需要在工程 pom.xml 中增加 org.springframework:spring-context-indexer 依賴:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-indexer</artifactId>
<optional>true</optional>
</dependency>
當工程打包為 JAR 或在 IDE 工具中重新構建后,METE-INF/spring.components 文件將自動生成。換言之,該文件在編譯時生成。當 Spring 應用上下文執行 @CompoentScan 掃描時,METE-INF/spring.components 將被 CandidateComponentsIndexLoader 讀取並加載,轉化為 CandidateComponentsIndex 對象,進而 @CompoentScan 不再掃描指定的 package,而是讀取 CandidateComponentsIndex 對象,從而達到提升性能的目的。
在Spring5.0當中的@Component注解當中,已經添加了該注解:
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Indexed public @interface Component { /** * The value may indicate a suggestion for a logical component name, * to be turned into a Spring bean in case of an autodetected component. * @return the suggested component name, if any (or empty String otherwise) */ String value() default ""; }
