The @Lazy annotation

By default, all autowired dependencies are created and initialized at startup, meaning the Spring IoC container creates all beans at the time of application startup; however, we can control this pre-initialization of beans at startup by using the @Lazy annotation.

The @Lazy annotation may be used on any class directly or indirectly annotated with @Component, or on methods annotated with @Bean. When we use the @Lazy annotation, that means the bean will be created and initialized only when it is first requested.

We know that annotation requires less code because we don't need to write the code to inject the dependency explicitly. It helps us reduce the development time, as well. Though annotation offers lots of advantages, it has its drawback, as well.

Disadvantages of annotation are as follows:

  • Less documentation than explicit wiring
  • If we have a lot of dependency in a program, then it's hard to find it by using the autowire attribute of bean
  • Annotation makes the process of debugging hard
  • It might give unexpected results in case of ambiguity
  • Annotation can be overridden by explicit configuration, such as Java or XML
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset