T3rm1
T3rm1

Reputation: 2584

How to improve Spring Boot startup time

Is it possible to improve the startup time of Spring Boot?

Here is an example of an empty CommandLineRunner project. The startup takes 914 milliseconds.

@SpringBootApplication
public class Main implements CommandLineRunner {

    private static long t1;

    public static void main(String[] args) {
        t1 = System.currentTimeMillis();
        SpringApplication.run(Main.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println(System.currentTimeMillis() - t1);    
    }

}

Upvotes: 2

Views: 4561

Answers (2)

Niraj Sonawane
Niraj Sonawane

Reputation: 11115

You can use Spring Framework 5.0 component index feature as an alternative to classpath scanning. to improve Boot Startup time.

This support has been added to shortcut the candidate component identification step in the classpath scanner.

An application build task can define its own META-INF/spring.components file for the current project.

At compilation time, the source model is introspected and JPA entities and Spring Components are flagged.

Reading entities from the index rather than scanning the classpath does not have significant differences for small projects with less than 200 classes.

However,

It has significant impacts on large projects. Loading the component index is cheap. Therefore, the startup time with the index remains constant as the number of classes increases.

You can find more details here JIRA

Update Other Option

Lazy Initialization feature in Spring Boot 2.2 Spring Boot 2.2 makes it easy to enable lazy initialization. Need to set spring.main.lazy-initialization to true to enable lazy initialization.

Note - lazy internalization has some advantages and disadvantages use it carefully. For more details please check This

Upvotes: 4

Andy Wilkinson
Andy Wilkinson

Reputation: 116271

Yes, it's possible, but it depends on what functionality you're happy to lose. For example, you could replace @SpringBootApplication with @SpringBootConfiguration and @ComponentScan which will switch off auto-configuration. You'll gain a few milliseconds in startup time but will now have to configure things yourself, or manually import auto-configuration classes that meet your application's needs.

Upvotes: 1

Related Questions