How to lazy initialize Spring beans?

Lazy Initiation in Spring IOC

As we know Spring’s bean factory is pre-initiate all the beans when first time creating the factory. This is good practice because if there is any dependency error everything can be resolved at the time of start up. This is not case in all the application scenarios. The following are the few drawbacks in pre-initiating all the beans at start up:

  • Takes long time to start the application. Since BeanFactory has to initiate all the beans even if it is unnecessary.
  • More memory for storing all the beans.

also read:

Based on the above impacts, some applications required beans to initiate only when they are required.Spring provides an attribute called lazy-init to inform the Spring IOC container for not creating that bean at the start up. lazy-init will be set as true to indicate the container. The beans will be created only when requested. Consider when there is a bean which is initiated at the startup. But, it has depends-on attribute pointing to the bean which is set as lazy-init=”true”. This case the can will be initiated without considering lazy-init value. lazy initialize is important concept to learn for managing the spring beans.

Look at the below example to understand this concept clearly.


/** * Source : */
public class Employee {
	private String name;
	private String empId;
	private Address address;

	public Employee() {
		System.out.println("Employee Constructor");

	public Address getAddress() {
		return address;

	public void setAddress(Address address) {
		this.address = address;

	public String getEmpId() {
		return empId;

	public void setEmpId(String empId) {
		this.empId = empId;

	public String getName() {
		return name;

	public void setName(String name) { = name;


/** * Source : */
public class Address {
	public Address() {
		System.out.println("Address Constructor");

	private String street;
	private String city;
	private String pincode;

	public String getCity() {
		return city;

	public void setCity(String city) { = city;

	public String getPincode() {
		return pincode;

	public void setPincode(String pincode) {
		this.pincode = pincode;

	public String getStreet() {
		return street;

	public void setStreet(String street) {
		this.street = street;

import org.springframework.context.ApplicationContext;
/** * source : */
public class LazyInit {
	public static void main(String args[]) {
		//Initializing context
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext( new String[]{"applicationContext.xml"});
		System.out.println("After initialization");

also read:


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
	xmlns:xsi="" xmlns:p=""
	xmlns:aop="" xmlns:tx=""
	<bean id="employeeBean" class="" />
	<bean id="addressBean" class=""
		lazy-init="true" />

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!