기본적으로 Spring의 ApplicationContext  구현은 초기화 프로세스에서 모든 싱글톤 빈을 생성 및 설정하게 된다.  초기화시 빈 생성/설정의 장점중 하나는 문제가 있을 경우 해당 빈을 사용할 때가 아닌 초기화 단계에서 바로 알 수 있다는 점이다

 어떤 이유로 특정 bean 은 늦게 초기화되기를 원한다면 bean 의 attribute 중 lazy-init 을 사용하여 조정할 수 있다.

 

lazy-init 은 "true", "false", "default" 세 가지의 옵션을 가질 수 있다. default 는 spring 의 기본 동작에 맞게 bean 을 생성하며 기본 동작은 false 이다. true 로 설정할 경우 나중에 Bean 을 생성하게 된다.

lazy-init="true" 로 설정해도 해당 bean 이 lazy-init="false" 인 bean 에서 참조된다면 의존성 관계로 인해 초기화 프로세스에서 생성되게 된다.

 

예제

Code

src/main/java/com/exmaple/First.java

package com.example;
public class First {
	public First() {
		System.out.println("Class First is initialized");
	}
}
CODE

src/main/java/com/exmaple/Second.java

package com.example;
public class Second {
	public Second() {
		System.out.println("Class Second Initialized");
	}
}
CODE

src/test/resources/spring-lazy.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	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-3.2.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd">
		
	<bean id="secondBean" class="com.example.Second" lazy-init="true" />
	
	<bean id="firstBean" class="com.example.First" lazy-init="default" />	
</beans>
XML

 

Test

LazyInitTest

 package com.example;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class LazyInitTest {
	@Test	
	public void LazyInitTest() {
		ApplicationContext context = new ClassPathXmlApplicationContext("spring-lazy.xml");
		System.out.println("Calling Second Bean");
		context.getBean("secondBean");
	} 
}
CODE

결과 

Class First is initialized
Calling Second Bean
Class Second Initialized
CODE

 

There is no content with the specified labels

 

Ref