Spring Boot program optimization
1. Lazy initialization of beans
Generally, there are many time-consuming tasks in SpringBoot, such as database connection establishment, initial thread pool creation, etc. We can delay the initialization of these operations to achieve the purpose of optimizing startup speed. The spring.main.lazy-initialization
attribute , and if configured as true, all beans will be initialized lazily.
spring:
main:
lazy-initialization: true
Second, create a scan index
After Spring5, the function is provided to solve the problem of slow scanning speed when there are too many classes spring-context-indexer
through the scanning index generated in advance . We just need to import dependencies and use annotations on startup classes. In this way, files will be generated after the program is compiled and packaged . When the scan class is executed, the index file will be read to improve the scanning speed.@ComponentScan
@Indexed
META-INT/spring.components
@ComponentScan
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-indexer</artifactId>
<optional>true</optional>
</dependency>
@Indexed
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
3. Upgrade the new version of SpringBoot
Every time SpringBoot is upgraded, it will perform some performance optimizations. The latest version has arrived 3
. Spring officials have done a very good job of performance optimization, which can greatly improve the compilation and startup speed of programs.