본문 바로가기
Web/Spring

7. [스프링] Bean 과 Singleton(싱글톤)의 관계

by jungwon3004 2022. 2. 2.
728x90
반응형

1. Bean 과 Singleton 의 관계

지금까지의 글을 통해 우리는 이제 Beanspring container 안에 생성된 object를 뜻한다는 것을 알게 되었다.

applicationContext.xml 파일에서 <bean>에 적어둔 내용을 바탕으로 id 이름, 즉 변수명을 정하고, 어떤 class의 instance인지 정해서 bean object를 만든다.

그리고 필요하면 java file에서 getBean() method를 통해 객체를 참조(ref)해서 가져온다.

 

여기서 중요한 포인트는 바로 "참조"했다는 점이다.

spring에서는 어떤 java 파일에서 getBean( ) 하든 똑같은 bean을 참조(ref)해서 가져온다.

 

왜냐하면 bean은 singleton (싱글톤)으로 생성되어 있기 때문이다.

 

상당히 놀랍지 않은가??

사실 java 코드를 짜다가 singleton 을 직접 사용할 일이 그렇게 많지는 않다.

굳이 사용한다고 치면, enum 타입을 사용할 때 정도??

 

(혹시 enum이 singleton인지 몰랐다면 참고해주세요)

https://moonsonghada.tistory.com/64

 

[JAVA] enum 이란? (아무리 봐도 이해가 안 된다면 꼭 보자)

1. enum enum은 사실 하나만 알면 된다. "enum은 singleton의 일종이다." 사실상 설명 끝!!! enum이라는 말은 Enumeration, 즉 "열거"의 약자이다. Enumeration Type과 Enumeration constant(열거상수)로 이루어져..

moonsonghada.tistory.com

 

아무튼 singleton이라는 걸 사용할 일이 자주 있지 않았기에 spring이라는 국내에서 가장 많이 사용하는 framework에서 bean object 생성을 singleton으로 한다는 사실이 처음 스프링을 배울 때 나에겐 굉장히 충격적이었다.

 

정리해보면, container에는 applicationContext.xml 에 적힌 bean 단 하나만 존재하며, getBean( ) 을 하더라도 매번 같은 object 가 reference되고 있다.

 

728x90
반응형

 

2. Singleton VS Prototype

물론 singleton으로만 생성해야만 하는 건 아니다.

그저 default type이 singleton이라는 것이다.

 

만약 getBean( ) 할 때마다 다른 객체를 생성해서 가져오고 싶다면 singleton이 아닌 prototype으로 생성하면 된다.

 

예를 들어, Dependency bean 하나와 Injection 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 id="injectionBean" class="scope.ex.InjectionBean" />
    
	<bean id="dependencyBean" class="scope.ex.DependencyBean" 
    	scope="prototype">
    	<constructor-arg ref="injectionBean" />
        <property name="injectionBean" ref="injectionBean" />
    </bean>
	
</beans>

<bean> tag의 속성(attribute)로 scope="prototype" 을 추가해주면 된다.

 

728x90
반응형