Jerry's Blog

Recording what I learned everyday

View on GitHub


28 April 2019

Spring(5)----Lazy-initialized Beans

by Jerry Zhang

#Tip of the Day:

1. Tomcat server, be careful with the Application context!

2. If we use Spring boot to start a server, we must add a dependency: spring-boot-starter-web



Video Link

What is lazy-init?

By default, Singleton is the scope of every bean. Every bean will be created when the Spring application is started. This means, no matter you use this bean or not, Spring container will create one for you.

If lazy-init is used, then only when we try to get this bean, Spring creates it for us.

Before using lazy-init

Create a bean as usual:

public class Bean {
    public Bean() {
        System.out.println("Bean has bean created");
    }
}

Register this bean:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <bean class="springioc.class010.Bean" id="bean"/>
    
</beans>

Test:

public class Class10Test {

    @Test
    public void test(){
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spring.xml");
        System.out.println("Context has been created");
        Bean bean = context.getBean("bean", Bean.class);
        System.out.println("bean = " + bean);
    }
}

Our result is:

Bean has bean created
Context has been created
bean = springioc.class010.Bean@e320068

This means Bean was created before creating our context and getBean, although we print our context first.

After using lazy-init

<bean class="springioc.class010.Bean" id="bean" lazy-init="true"/>

The result now is:

Context has been created
Bean has bean created
bean = springioc.class010.Bean@1b68ddbd
tags: Java, - Spring, - Spring - framework, - Bean, - Lazy-initialized