[Spring] Spring Bean Scope

0. 출처

아직 배우고 있는 중이라 부정확한 정보가 포함되어 있을 수 있습니다!
주의하세요!

올인원 스프링 프레임워크 참고.

https://search.shopping.naver.com/book/catalog/41101295635?cat_id=50010920&frm=PBOKPRO&query=%EC%98%AC%EC%9D%B8%EC%9B%90+%EC%8A%A4%ED%94%84%EB%A7%81+%ED%94%84%EB%A0%88%EC%9E%84%EC%9B%8C%ED%81%AC&NaPm=ct=lma2t8xk%7Cci=a48cf03f14ef65da3f75709822c7b195a41bd691%7Ctr=boknx%7Csn=95694%7Chk=dba64f780dac99af3b6dc40908ddb18778aaa3a1


1. Spring Bean Scope

https://docs.spring.io/spring-framework/docs/3.0.0.M3/reference/html/ch04s04.html

  • Spring Bean Scope
    : Spring Framework에서 Bean의 생명주기와 가시성을 정의하는 속성.
ScopeDescription
singletonScopes a single bean definition to a single object instance per Spring IoC container.
prototypeScopes a single bean definition to any number of object instances.
requestScopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
sessionScopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
global sessionScopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.

가. 싱글톤

스프링 빈 범위 (spring bean scope) = singleton

IoC 컨테이너에서 생성된 Bean을 getBean()으로 호출하면 동일한 객체를 반환한다.

개발자가 별도로 명시하지 않으면 스프링은 기본적으로 객체 범위를 싱글톤으로 관리한다.

<bean id="accountService" class="com.foo.DefaultAccountService"/>

<!-- the following is equivalent, though redundant (singleton scope is the default); using spring-beans-2.0.dtd -->
<bean id="accountService" class="com.foo.DefaultAccountService" scope="singleton"/>

<!-- the following is equivalent and preserved for backward compatibility in spring-beans.dtd -->
<bean id="accountService" class="com.foo.DefaultAccountService" singleton="true"/>
Code language: HTML, XML (xml)

요청마다 인스턴스를 새로 생성하지 않고 하나의 인스턴스를 재활용한다.

getbean()으로 bean을 가져올 때마다 새로운 bean이 생성되는 것이 아니라 동일한 bean이 계속해서 사용된다.

메모리에 단 하나의 인스턴스만 있기 때문에 메모리 사용이 효율적이다.


나. 프로토타입

스프링 빈 범위 (spring bean scope) = prototype

singleton과 반대로 getbean()으로 bean을 가져올 때마다 새로운 bean을 생성한다.

이는 동명의 Prototype 디자인 패턴과 관련있다.

Prototype 디자인 패턴은 객체를 생성할 때마다 기존 객체를 복제하여 새 객체를 생성한다.

Prototype 패턴은 객체 생성에 필요한 초기 설정이나 계산 비용을 줄이고, 런타임에 객체 생성을 유연하게 처리할 수 있도록 도와준다.

Prototype 패턴은 기존 객체의 현재 상태를 캡처하고 이 상태를 사용하여 새 객체를 빠르게 생성한다.

이는 일반적으로 객체 생성에서 발생하는 비용(생성자를 호출, 초기화 등)을 아낄 수 있다. (특히, 객체가 복잡한 초기 구성을 필요로 하거나, 객체의 상태를 구성하기 위해 외부 리소스에 액세스해야 할 때)

또한 런타임에서 객체의 구체적인 형태가 결정되는 경우에 활용될 수 있다.

객체를 런타임에 구체화하고, 이를 필요한 곳에 복제해서 공급할 수 있다.

<!-- using spring-beans-2.0.dtd -->
<bean id="accountService" class="com.foo.DefaultAccountService" scope="prototype"/>

<!-- the following is equivalent and preserved for backward compatibility in spring-beans.dtd -->
<bean id="accountService" class="com.foo.DefaultAccountService" singleton="false"/>
Code language: HTML, XML (xml)


다. 싱글톤 vs 프로토타입

결론:

  • Singleton
    : 메모리 효율성이 중요하고, 상태 공유가 필요할 때.
  • Prototype
    : 각 요청이 독립적, 멀티스레드 환경에서 더 안정적인 동작이 필요.

댓글 남기기