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一样在编译期处理。

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐