Saturday, November 2, 2019

Spring Boot: Lazy Initialization Of Beans

Many times we don't want to load all the beans at the application start up. We want beans to come into existence when an actual call is made to them.

It could be the case where many of the beans never used, but loaded in context at the startup.

Isn't it waste of app startup time and memory as well.

Spring boot provides very easy way to enable lazy initialization of beans.

1. Using Property file:

              spring.main.lazy-initialization=true

The above will ensure all the beans are initialized when only required.

Lazily loading all beans could be problematic as well
1. It can suppress exceptions,
2. Memory overflow
3. In case of HTTP calls high throughput time,
4. Can confuse load balancer etc.

2. Using @Lazy Annotation: To target a specific bean to lazily load.

Just Remember if you are using @Lazy at the component level and adding that component using @Autowired, you mandatorily add @Lazy at both the places (i.e. @Component & @Autowired) for it to work.

We can use @Lazy(false) as well along with property file to lazily load all beans except the bean annotated with @Lazy(false)


@Component
@Lazy
public class MyLazyBean {
      public MyLazyBean() {
       log.info("MyLazyBean initialized");
    }
}

Public class App {
    @Lazy
    @Autowired
    private MyLazyBean mlb;
}
@Lazy @Configuration
public class ConfigClass { @Bean private A getA(){ return new A(); }
 @Bean  
 private B getB(){
   return new B();
 }
}

No comments: