Spring component annotation compile time scan

白昼怎懂夜的黑 提交于 2019-11-29 18:40:38

问题


My belief is that the Spring bootstraps

  • ContextLoaderListener
  • DispatcherServlet

due to the instruction

<context:component-scan base-package=" ..... " />

would perform component scans at app startup (or whenever instructed to) during run-time.

Is there a way to instruct the compiler (perhaps thro a maven build plugin) to perform a one time static scan of annotated spring components during build/compile time, so that the bootstrap component scan is not performed, WITHOUT abandoning the use of component annotation?

As a way to reduce startup load and latency.


回答1:


Spring 5 Has added a new feature to improve startup performance of large applications.

it creates a list of component candidates at compilation time.

In this mode, all modules of the application must use this mechanism as, when the ApplicationContext detects such index, it will automatically use it rather than scanning the classpath.

To generate the index, we just need to add below dependency to each module

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")
}

This process will generate a META-INF/spring.components file that is going to be included in the jar.

Reference : 1.10.9. Generating an index of candidate components




回答2:


Spring 5 has added an option of generating an index of candidate components at compile time. When the index is found, only the index is used and full classpath scan is skipped.



来源:https://stackoverflow.com/questions/25981158/spring-component-annotation-compile-time-scan

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!