본문 바로가기
Spring

230130 Spring Bean

빈(Bean)의 범위

 

싱글톤(SingleTon)

스프링 컨테이너에서 생성된 빈(bean)객체의 경우 동일한 타입에 대해서는 기본적으로
한 개만 생성이 되며, getBean()메서드로 호출될 때 동일한 객체가 반환된다.

 

프로토타입(Prototype)

쓸일은 거의 없다
싱글톤 범위와 반대의 개념
스프링 설정 파일에서 빈객체를 정의할 때 scope속성을 명시해 주면 된다. scope="prototype"

자동으로 싱글톤이며, 싱글톤으로 사용할 것.


MainClass.java

package ex01;

import org.springframework.context.support.GenericXmlApplicationContext;

public class MainClass {
	public static void main(String[] args) {
		
		GenericXmlApplicationContext ctx=
		new GenericXmlApplicationContext("application-context.xml");
		
		//SpringTest bean=ctx.getBean(SpringTest.class);
		//bean.test();
	
    		SpringTest bean=(SpringTest)ctx.getBean("test");
		bean.test();
		
	}
}

->getBean을 이름으로 가져와서 형변환을 해줬다.

->SpringTest객체를 생성하지 않았다! 

 

SpringTest.java

package ex01;

public class SpringTest {

	public void test() {
		System.out.println("스프링 bean 사용해보기");
	}
}

 

application-context.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="test" class="ex01.SpringTest"/>


</beans>

 

 

결과 콘솔창

1월 30, 2023 7:19:48 오후 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [application-context.xml]
1월 30, 2023 7:19:48 오후 org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.GenericXmlApplicationContext@402a079c: startup date [Mon Jan 30 19:19:48 KST 2023]; root of context hierarchy
스프링 bean 사용해보기

 


기본적으로 싱글톤 방식인 것을 확인할 것.

위와 같은 코드 내에서,

 

application-context.xml을

<!-- 스프링 빈 설정 파일 -->
<bean id="test" class="ex01.SpringTest" scope="prototype"/>

로,

 

메인을

package ex01;

import org.springframework.context.support.GenericXmlApplicationContext;

public class MainClass {
	public static void main(String[] args) {
		
		GenericXmlApplicationContext ctx=
		new GenericXmlApplicationContext("application-context.xml");
		
		SpringTest bean=(SpringTest)ctx.getBean("test");
		SpringTest bean2=(SpringTest)ctx.getBean("test");
	
		System.out.println(bean==bean2);

		
	}
}

로 바꾸고 출력했을 때

System.out.println(bean==bean2);의 결과는 false로 나온다.

bean 속성에 scope="prototype"을 주지 않으면 true로 나온다.

 

//false-> prototype 형태

//true-> singleton 형태