Close

Spring - Lazy Initialization, using @Lazy

[Last Updated: Mar 14, 2021]

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 not be a good idea if they are going to use considerable resources/memory to get initialized. In those 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 annotation on bean configuration method.




Example

An example bean which is used rarely

package com.logicbig.example.bean;

import javax.annotation.PostConstruct;

public class RarelyUsedBean {

  @PostConstruct
  private void initialize() {
      System.out.println("RarelyUsedBean initializing");
  }

  public void doSomething() {
      System.out.println("RarelyUsedBean method being called");
  }
}

An example bean which is used frequently

package com.logicbig.example.bean;

import javax.annotation.PostConstruct;

public class AlwaysBeingUsedBean {

  @PostConstruct
  public void init() {
      System.out.println("AlwaysBeingUsedBean initializing");
  }
}

Using @Lazy annotation and running main class

package com.logicbig.example;

import com.logicbig.example.bean.AlwaysBeingUsedBean;
import com.logicbig.example.bean.RarelyUsedBean;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

@Configuration
public class AppConfig {

  @Bean
  public AlwaysBeingUsedBean alwaysBeingUsedBean() {
      return new AlwaysBeingUsedBean();
  }

  @Bean
  @Lazy
  public RarelyUsedBean rarelyUsedBean() {
      return new RarelyUsedBean();
  }

  public static void main(String... strings) {
      AnnotationConfigApplicationContext context =
              new AnnotationConfigApplicationContext(AppConfig.class);
      System.out.println("Spring container started and is ready");
      RarelyUsedBean bean = context.getBean(RarelyUsedBean.class);
      bean.doSomething();
  }
}

Output

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

Example Project

Dependencies and Technologies Used:

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

Lazy Initialization, using @Lazy Select All Download
  • spring-lazy-loading
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • bean
                • AppConfig.java

    See Also