【问题标题】:How can I create a Spring 5 component index?如何创建 Spring 5 组件索引?
【发布时间】:2018-04-25 13:53:54
【问题描述】:

Spring Framework 5 显然包含对“组件索引”的支持,该索引位于 META-INF/spring.components 中,可用于避免对类路径扫描的需要,因此,我认为可以改进 webapps 的启动时间。

见:

如何为我计划升级到 Spring 5 的现有 Web 应用创建这样的组件索引?

(理想情况下,我想它会在构建时使用 Maven 自动生成,但任何其他可行的方法至少会给我一个工作起点)

【问题讨论】:

  • 您是否已经检查过Stephane Nicoll's repo,它通过了一些测试示例?这些示例似乎利用dependency in the pom 基于带注释的@Components 构建此索引
  • 啊,不,我没找到 - 谢谢,我去看看!
  • 你运气好吗?我尝试在我的 pom 中包含 spring-context-indexer,但在加载时间上没有看到任何差异,而且我没有看到创建的索引文件。到目前为止,我还不能让这个工作
  • 还没有回复很抱歉 - 如果/当我回复时,我一定会报告。
  • @Zipper 它对我很有用。它附加到一个 Maven 目标,特别是包目标,所以我所要做的就是运行 mvn package 并创建我的索引文件。

标签: java spring maven spring-mvc


【解决方案1】:

Spring 5添加了一项新功能以提高大型应用程序的启动性能。

它在编译时创建一个候选组件列表。

在这种模式下,应用程序的所有模块都必须使用这种机制,因为当ApplicationContext检测到这样的索引时,它会自动使用它而不是扫描类路径。

要生成索引,我们只需要为每个模块添加以下依赖项

Maven:

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

Gradle

dependencies {
    compileOnly("org.springframework:spring-context-indexer:5.0.3.RELEASE")
}

此过程将生成一个 META-INF/spring.components 文件,该文件将包含在 jar 中。

参考:1.10.9. Generating an index of candidate components

【讨论】:

  • 是的 - 有趣 - 我会在某个时候试一试。不过,这里的机制(至少在 maven 中)正在向模块添加依赖项,这似乎非常奇怪——我原以为它是一个 maven 插件或类似的东西。生成过程中究竟发生在什么时候?
  • 如果您阅读文档说它需要在 IDE 中使用 annotation-processor在 IDE 中使用此模式时,spring-context-indexer 必须注册为注释处理器,以确保更新候选组件时索引是最新的。 !我认为它没有与 maven 集成 :-(
  • 终于回来试一试(如果重要,使用 provided 而不是 optional=true),它确实会创建一个 spring.compoents 文件 -我猜添加依赖项会导致应用注释处理器(并且 scope=provided 避免实际打包 jar)。不幸的是,由于某种原因,导致的战争未能部署并出现“无合格 bean”异常,但这是一个不同的问题 - 谢谢。
  • 啊,我的问题似乎是我需要所有还创建 bean 的依赖项才能拥有 spring.components,所以在确保它之后我让它工作 - 可悲的是,它似乎有对整体启动时间的影响很小(看起来平均最多可以节省大约 1 秒)。
  • 但是对于 jar 依赖,这是行不通的。你能看看这个stackoverflow.com/questions/53718184/…
【解决方案2】:

META-INF/spring.components 文件由名为 spring-context-indexer 的注释处理器库生成。如果将此库作为“注释处理器路径”添加到 maven-compiler-plugin,则文件将在构建时自动生成:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId>
  <configuration>
    <annotationProcessorPaths>
      <path>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-indexer</artifactId>
        <version>5.0.6.RELEASE</version>
      </path>
    </annotationProcessorPaths>
    ...
  </configuration>
</plugin>

此设置需要 maven-compiler-plugin 3.5 或更高版本。

另请参阅:https://maven.apache.org/plugins/maven-compiler-plugin/compile-mojo.html#annotationProcessorPaths

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-08
    • 1970-01-01
    • 1970-01-01
    • 2021-05-11
    • 2017-04-04
    • 2019-08-15
    • 1970-01-01
    相关资源
    最近更新 更多