Spring – @Lazy Loading

By default, Spring “application context” eagerly creates and initializes all ‘singleton scoped‘ beans during application startup itself. It helps in detecting the bean configuration issues at early stage, in most of the cases. But sometimes, you may need to mark some or all beans to be lazy initialized due to different project requirements.

Spring provides two easy ways to configure lazy initialization of beans based on which kind of configuration you are employing i.e. XML based configuration or java based configuration.

Table of Contents

1. Lazy initialized beans in Java configuration
2. Lazy initialized beans in XML configuration

1. @Lazy initialized beans – Java configuration

1.1. @Lazy load specific bean

To lazy load only specific beans, use @Lazy annotation along with @Bean annotation in java config.

import org.springframework.context.annotation.Lazy;

@Configuration
public class AppConfig {
	
    @Lazy
    @Bean
    public EmployeeManager employeeManager() {
        return new EmployeeManagerImpl();
    }
	
}

1.2. Lazy load all beans

To lazy load all beans, use @Lazy annotation along with @Bean annotation in java config.

import org.springframework.context.annotation.Lazy;

@Lazy
@Configuration
public class AppConfig {
	
    @Bean
    public EmployeeManager employeeManager() {
        return new EmployeeManagerImpl();
    }
	
}

1.3. @Autowired lazy beans

Generally, beans are injected into other components using @Autowired annotation. In this case, we must use the lazy annotation at both places:

  • The bean definition which you want to lazy load
  • The place it is injected along with @Autowired annotation
@Lazy
@Service
public class EmployeeManagerImpl implements EmployeeManager {
  //
}
@Controller
public class EmployeeController {

	@Lazy
	@Autowired
	EmployeeManager employeeManager;
}

Without using @Lazy annotation at both places, it will not work.

2. Lazy initialized beans in XML configuration

2.1. Lazy load specific beans only

To enable lazy loading for specific beans, use lazy-init=”true” attribute on bean definitions in bean configuration xml files.

<beans>

<bean id="employeeManager" class="com.howtodoinjava.spring.service.impl.EmployeeManagerImpl" 
	lazy-init="true"/>

<beans>

2.2. Lazy load all beans globally

To enable lazy loading for all beans, use default-lazy-init=”true” attribute on beans tag in bean configuration xml files.

<beans default-lazy-init="true">

<bean id="employeeManager" class="com.howtodoinjava.spring.service.impl.EmployeeManagerImpl" />

<beans>

3. Spring lazy loading demo

Let’s see the code of bean, we are trying to lazy load.

@Lazy
@Service
public class EmployeeManagerImpl implements EmployeeManager {

	@Override
	public Employee create() {
		Employee emp =  new Employee();
		emp.setId(1);
		emp.setName("Lokesh");
		return emp;
	}
	
	@PostConstruct
	public void onInit(){
		System.out.println("EmployeeManagerImpl Bean is Created !!");
	}
}

I have put the @PostConstruct annotation to detect when bean is created.

Lets initialize the application context with –

3.1. Without Lazy loading

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.howtodoinjava.spring.model.Employee;
import com.howtodoinjava.spring.service.EmployeeManager;

public class Main 
{
    public static void main( String[] args )
    {
    	ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
    	
    	System.out.println("Bean Factory Initialized !!");
        
    	EmployeeManager empManager = ctx.getBean(EmployeeManager.class);
    	Employee emp = empManager.create();
    	
    	System.out.println(emp);
    }
}

Program output.

EmployeeManagerImpl Bean is Created !!
Bean Factory Initialized !!
Employee [id=1, name=Lokesh]

Here, first bean has been created and initialized before the bean factory got fully initialized.

3.2. With Lazy loading

Bean Factory Initialized !!
EmployeeManagerImpl Bean is Created !!
Employee [id=1, name=Lokesh]

After enable bean lazy loading, bean factory first for fully initialized. Later when we requested the EmployeeManager bean, factory then created the instance and returned it.

Drop me your questions in comments section related to difference between lazy loading and eager loading in Spring.

Happy Learning !!

Leave a Reply

12 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial