티스토리 뷰

[JAVA]/Spring

[Spring] Bean 객체의 범위

춘햄 2021. 6. 14. 14:47

스프링은 기본적으로 하나의 빈 설정에 대해 1 개의 객체만의 생성한다
즉, xml 에서 생성한 bean 객체의 Scope 기본값은 객체 맴버를 재사용하는 singleton 이다.

 

bean 태그의 scope 속성값은 다음과 같다.


이해를 위해 예제를 하나 확인해보면, 

 

◎BeanTest

package test.exam05;

public class BeanTest {

	public BeanTest() {

	}
	
	public void printTest() {
		System.out.println("안녕하세요");
	}

}

 

◎exam.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"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean name = "beanTest" class = "test.exam05.BeanTest">
	
	</bean>

</beans>

 다음과 같이 bean 객체 내부에 scope 속성을 명시하지 않았다면, scope의 default인 singleton으로 설정된다.

 

◎main

package test.exam05;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class ExamMain {

	public static void main(String[] args) {
		ApplicationContext context = new FileSystemXmlApplicationContext("/src/test/exam05/exam06.xml");
		BeanTest beanTest1 = (BeanTest)context.getBean("beanTest");
		BeanTest beanTest2 = (BeanTest)context.getBean("beanTest");
		
		System.out.println("beanTest1 : " + beanTest1);
		System.out.println("beanTest2 : " + beanTest2);
	}

}

이 상태에서 객체를 다중으로 생성하게 되면, 결과는 다음과 같이, 같은 주소값을 사용하는 것을 확인할 수 있다.


그러나 다음과 같이 scope = prototype 으로 설정하면,

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean name = "beanTest" class = "test.exam05.BeanTest" scope = "prototype">
	
	</bean>

</beans>

위와 같이 다른 주소값을 참조하는 걸 확인할 수 있다.

Comments