Spring - Lazy Initialization, using @Lazy

[Updated: Jan 28, 2017, Created: Dec 5, 2015]

By default Spring container instantiates all configured beans at startup (eager loading). In some situations, however, beans might rarely be used during application life cycle. Loading them at startup will, specially, be not good if they are going to use considerable memory to get initialized. In those sort of situations we may decide to initialize such beans only when they are first accessed by application code (i.e. initialize on demand). We can achieve that by using @Lazy on bean configuration method.






Example Project

Dependencies and Technologies Used :

  • Spring Context 4.2.3.RELEASE: Spring Context.
  • JDK 1.8
  • Maven 3.0.4

Spring Lazy Loading Example Select All Download
  • spring-lazy-loading
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • bean

On running AppConfig#main we will get following output.

AlwaysBeingUsedBean initializing
Spring container started and is ready
RarelyUsedBean initializing
RarelyUsedBean method being called

Notice RarelyUsedBean initializes after Spring container start up.

Now in AppConfig class, comment out @Lazy on rarelyUsedBean() method and run the main method again. See the difference:

RarelyUsedBean initializing
AlwaysBeingUsedBean initializing
Spring container started and is ready
RarelyUsedBean method being called


@PostConstruct/@PreDestroy vs Spring "init-method"/"destroy-method" configuration

In above example, we used JSR-250 annotation: @PostConstruct. Which is better than spring counterpart configuration of "init-method" on the @Bean.

  • Firstly the bean itself is saying 'I need to do some post construct processing' rather than the configuration class (annotated with @Configuration) is in charge and asking the bean: 'You need to do some post construct processing'. Conceptually, the post construct processing should be internal detail of the bean and should not be the concerns of oursiders.
  • Secondly we are putting a type safe annotation on the bean method rather than specifying init-method name as String (not type safe) on @Bean.

See Also