Reduce Startup Time with Spring Boot 2.2


19 Mar 2019  Sergio Martin Rubio  2 mins read.

Spring Boot 2.2 will be released soon (currently 2.2.0 M1) and it’s going to bring some improvement and new features like lazy initialization of beans.

Until now spring-boot-devtools was the only way to see changes without having to restart the whole application. Whenever there are changes in your classpath folder(s) DevTools will take the appropriate action to apply those changes. However, for IDEs like IntelliJ, adding this dependency is not enough, and you also have to:

  1. Enable the “Make project automatically” option. You can find it in Settings – Build, Execution, Deployment – Compiler
IntelliJ Settings
IntelliJ Settings
  1. Open the registry, just press SHIFT+CTRL+ALT+/ (Ubuntu 18.04). In the registry window, enable the “compiler.automake.allow.when.app.running” check-box.
IntelliJ Registry
IntelliJ Registry

Another alternative offered by DevTools is to explicitly tell IntelliJ IDEA to run “Build Project” (CRLT+9 in Ubuntu 18.04) to build the target classpath. This feature is also available since Spring Boot 2 when running the application in Debug Mode.

On the other hand, the latest Spring Boot version offers an additional alternative. With the version 2.2 your beans can be initialized lazily by setting a System Property.

spring.main.lazy-initialization=true

If this property is set to true your beans will be initialized only when they are needed. For instance, if you have a dependency in your pom file to setup a DB connection, this will not happen until the connection is required. As you can imagine this can cause unexpected behaviors, so make sure you only use this during development. Moreover, this could slow down some functionalities of your application when they run for the first time, since it will need to initialize the required beans, and will not show failures until later, instead of during start up.

spring.main.lazy-initialization=false
spring.main.lazy-initialization=false
spring.main.lazy-initialization=true
spring.main.lazy-initialization=true

As you can see in the previous examples, when the property is set to false, some connection errors are thrown, and the start up time is around 1.5 seconds. whereas, when it is set to true, no failures are displayed and start up time is around 1 second.