Spring中@ComponentScan扫描的package包含的类越多的时候,Spring模式注解解析耗时就越长,服务启动时候就越长,针对此问题Spring提供了@Indexed注解来添加索引。
查看@Serive、@Controller、@Repository、@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 "";
}
在项目的添加spring-context-indexer的依赖
maven中:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-indexer</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
gradle中
annotationProcessor 'org.springframework:spring-context-indexer'
gradle4.5以下使用
compileOnly "org.springframework:spring-context-indexer"
这样启动效率就提升啦。
会发现在编译后生成了META-INF/spring.components文件
@Indexed,可以预编译,跟lombok一样在编译期处理。