Spring bean Lazy loading annotation example

The Spring bean Lazy loading annotation example show you how to use @Lazy annotation together with @Component and @Autowired annotation. Spring container is eagerly loading all autowired dependencies at startup by default. In case, we want to mark a bean is lazy loading, we have to annotated @Lazy annotation on the bean as well at the point where it is @Autowired in. This is because if you don’t have @Lazy on the bean, then it is eagerly created, and if you have don’t have an @Lazy on the @Autowired then again it is eagerly created and injected into the bean.

Decclare @Lazy and @Autowired annotation
In this example, we create two beans named University and Student. The University bean is annotated with the @Lazy annotation, which make a bean is to be lazily initialized.

The Student bean will be created eagerly and autowired the University bean. But the autowired University bean is annotated with the @Lazy annotation too, which makes the Spring container to initialize the bean at first request.

Spring Configuration
This example is using annotations and components so we need to enable component scanning and annotation configuration by adding the element in spring-confix.xml file like below:

We create the main class and print messages which indicate what bean is loading and when.

Running the above main and the output is printed like below:
Spring bean Lazy loading annotation example

Look at the output, you see the University bean is lazy loaded.

That’s all on the Spring bean Lazy loading annotation example.

@Lazy JavaDoc
Spring bean Lazy loading xml

Download complete source code, click link below

spring-bean-lazy-loading-annotation-example.zip (282 downloads)

If you found this useful, please share it with your friends

Leave a Comment


Please share it if you found this useful
Hide Buttons