Lazy Initialise

Components can be lazy-initialised — only initialise when it's needed.

To turn it on, add in application.yml

spring:  
  main:  
    lazy-initialization: on

As a result, it's only intialise when we're using it.

For example, consider the following:

@Component  
public class MyComponent {  
  private static final Logger logger = LoggerFactory.getLogger(MyComponent.class);  
  public MyComponent() {  
    logger.info(logger.getClass().getName());  
    logger.info("My component is created");  
  }  
}
@RestController  
public class MyController {  
  private final MyComponent myComponent;  
  
  public MyController(MyComponent myComponent) {  
    this.myComponent = myComponent;  
  }  
  
  @RequestMapping(value = "/", method = RequestMethod.GET)  
  public String home() {  
    return "Hello world 1";  
  }  
}

As a result, only when the user visit /, the log My component is created will be printed out.

By default without lazy-initialization, the log My component is created will always be printed out.

[!danger]
Using lazy-initialization if there is an error in our application during compilation, it will not be printed out. However it will improve application start-up time.