Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring component annotation compile time scan

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.

like image 723
Blessed Geek Avatar asked Sep 22 '14 18:09

Blessed Geek


People also ask

What is @ComponentScan annotation in Spring?

One of the most important annotations in spring is @ComponentScan which is used along with the @Configuration annotation to specify the packages that we want to be scanned. @ComponentScan without arguments tells Spring to scan the current package and all of its sub-packages.

What is use of @component annotation?

@Component is an annotation that allows Spring to automatically detect our custom beans. In other words, without having to write any explicit code, Spring will: Scan our application for classes annotated with @Component. Instantiate them and inject any specified dependencies into them.

What is difference between @component and @ComponentScan?

How They Differ. The main difference between these annotations is that @ComponentScan scans for Spring components while @EnableAutoConfiguration is used for auto-configuring beans present in the classpath in Spring Boot applications.

What is difference between @component and @bean in Spring?

@Component auto detects and configures the beans using classpath scanning whereas @Bean explicitly declares a single bean, rather than letting Spring do it automatically.


1 Answers

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

like image 127
Niraj Sonawane Avatar answered Nov 11 '22 02:11

Niraj Sonawane