일일구름 IT

[Spring] bean의 범위 (Prototype) 본문

Spring

[Spring] bean의 범위 (Prototype)

일구름 2023. 11. 7. 21:29

Bean의 범위

Spring에서 스프링 컨테이너에 생성된 Bean 객체는 getBean() 메소드로 호출될때 항상 같은 객체가 반환된다.

Bean 객체를 호출할때마다 다른 객체로 반환되기 위해서는 Bean 객체를 정의할때 scope 속성을 prototype으로 명시해주면 된다.

 

다음의 코드와 결과를 보며 싱글톤과 프로토타입의 차이를 확인해보자.

// MainClass.java 파일
public static void main(String[] args) {
	GenericXmlApplication ctx = new GenericXmlApplicationContext("classpath:applicationContext.xml");
    
    InjectionBean injectionBean = ctx.getBean("injectionBean", InjectionBean.class);
    
    DependencyBean dependencyBean01 = ctx.getBean("injectionBean", InjectionBean.class);
    DependencyBean dependencyBean02 = ctx.getBean("injectionBean", InjectionBean.class);
    
    if(dependencyBean01.equals(dependencyBean02)) {
    	System.out.println("dependencyBean01 == dependencyBean02");
	} else {
    	System.out.println("dependencyBean01 != dependencyBean02");
    }
// DependencyBean.java 파일
public class DependencyBean {
	private InjectionBean injectionBean;
    
    // 생성자
    public DependencyBean(InjectionBean injectionBean) {
    	System.out.println("DependencyBean : constructor");
        this.injectionBean = injectionBean;
    }
    
    // setter
    public void setInjectionBean(InjectionBean injectionBean) {
    	System.out.println("DependencyBean: setter");
        this.injectionBean = injectionBean;
     }

 

싱글톤일 경우

// applicationContext.xml
<?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 id="injectionBear" class="scope.ex.InjectionBean" />
    
    <bean id="dependencyBean" class="scope.exDependencyBean">
    	<constructor-arg ref="injectionBean" />
        <property name="injectionBean" ref="injectionBean" />
    </bean>
</beans>

 

결과

 

 

프로토타입일 경우

// applicationContext.xml
<?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 id="injectionBear" class="scope.ex.InjectionBean" />
    
    <bean id="dependencyBean" class="scope.exDependencyBean" scope="prototype">
    	<constructor-arg ref="injectionBean" />
        <property name="injectionBean" ref="injectionBean" />
    </bean>
</beans>

 

결과