Spring spring-context-indexer依赖 Spring之spring-context-indexer依赖详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Spring spring-context-indexer依赖 Spring之spring-context-indexer依赖详解

王哲晓   2021-11-09 我要评论
想了解Spring之spring-context-indexer依赖详解的相关内容吗,王哲晓在本文为您仔细讲解Spring spring-context-indexer依赖的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Spring依赖,spring-context-indexer依赖,下面大家一起来学习吧。

Spring spring-context-indexer依赖

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-indexer</artifactId>
        <version>5.2.0.RELEASE</version>
        <optional>true</optional>
    </dependency>
</dependencies>

虽然类路径扫描非常快,但是Spring内部存在大量的类,添加此依赖,可以通过在编译时创建候选对象的静态列表来提高大型应用程序的启动性能。

在此模式下,作为组件扫描目标的所有模块都必须使用此机制。

配置springboot启动时自动打开浏览器 spring-context-indexer原理

int port = 8080;
String portPrefix = "--server.port=";
for (String arg : args) {
    if (arg.startsWith(portPrefix)) {
        port = Integer.parseInt(arg.substring(portPrefix.length()));
    }
}
SpringApplication.run(AppRegisterApplication.class, args);
try {
    Runtime.getRuntime().exec("cmd /c start http://localhost:" + port);
} catch (IOException e) {
    e.printStackTrace();
}

现在使用的springboot 项目大了, 每次启动都非常的慢, 所有有了以下的依赖, 加速启动:

spring-context-indexer

说明

1.虽然类路径扫描非常快,但是Spring内部存在大量的类,添加此依赖,可以通过在编译时创建候选对象的静态列表来提高大型应用程序的启动性能。

2.但是在此模式下,作为组件扫描目标的所有模块都必须使用此机制。才可以。

3.需要spring5以上才能使用,亲测有效, 依赖如下:

<dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-indexer</artifactId>
        <version>5.2.0.RELEASE</version>
        <optional>true</optional>
</dependency>

然后再你的启动类上加上一个注解: @Indexed ,用来表示, 你开启了索引, 会加速项目的启动速度.

原理说明:

先看官方的解释:

在项目中使用了@Indexed之后,编译打包的时候会在项目中自动生成META-INT/spring.components文件。

当Spring应用上下文执行ComponentScan扫描时,META-INT/spring.components将会被CandidateComponentsIndexLoader 读取并加载,转换为CandidateComponentsIndex对象,这样的话@ComponentScan不在扫描指定的package,而是读取CandidateComponentsIndex对象,从而达到提升性能的目的.

使用需注意点

虽然这个@Indexed注解能提升性能,但是在使用的时候也需要注意一一下。

假设Spring应用中存在一个包含META-INT/spring.components资源的a.jar,b.jar仅存在模式注解,那么使用@ComponentScan扫描这两个JAR中的package时,b.jar 中的模式注解不会被识别。

请务必注意这样的问题。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们