본문 바로가기

SpringFramework Core - I. IoC 컨테이너/5. Bean Scopes

5.5.2. 커스텀 Scope 사용하기

원문: https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#beans-factory-scopes-custom-using

 

 

하나 이상의 커스텀 Scope 구현체를 생성하고 테스트하고나면 스프링 컨테이너가 이 새로운 scope를 알아보도록 해야한다. 다음 메소드는 스프링 컨테이너에 새로운 Scope를 등록하기 위한 주요 메소드이다.

void registerScope(String scopeName, Scope scope);

이 메소드는 ConfigurableBeanFactory 인터페이스에 선언되어 있으며, BeanFactory의 프로퍼티를 통해 사용가능하다. 따라서 BeanFactory의 구현체이면서 스프링을 담고있는 대부분의 ApplicationContext들에서 사용가능하다. 

 

registerScope() 메소드의 첫번자 인자는 scope의 유일한 이름이다. 스프링 컨테이너가 가진 이름들의 예시로는 singleton과 prototype이 있다. 두번째 인자는 여러분이 등록하고 사용하고 싶은, 커스텀 Scope 구현체의 실제 인스턴스이다.

 

커스텀 Scope 구현체를 정의했다고 가정하고 다음 예시처럼 등록해보자.

 

 다음 예시는 SimpleThreadScope를 사용한다. 기본값은 아니지만 스프링에 포함된 것이다. 커스텀 Scope 구현체와 방법이 같을 것이다.

Scope threadScope = new SimpleThreadScope();
beanFactory.registerScope("thread", threadScope);

그리고나서, 다음과 같이 커스텀 Scope에 의해 scoping되는 bean 정의를 생성할 수 있다.

<bean id="..." class="..." scope="thread">

커스텀 Scope 구현체를 사용했기 때문에 scope의 등록에 프로그래밍적으로 제한이 생기지는 않는다. 다음 예시처럼 CustomScopeConfigurer 클래스를 사용함으로써 Scope 등록을 선언적으로 할 수도 있다.

<?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:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">
        
    <bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
        <property name="scopes">
            <map>
                <entry key="thread>
                    <bean class="org.springframework.context.support.SimpleThreadScope" />
                </entry>
            </map>
        </property>
    </bean>
    
    <bean id="thing2" class="x.y.Thing2" scope="thread">
        <property name="name" value="Rick" />
        <aop:scoped-proxy/>
    </bean>
    
    <bean id="thing1" class="x.y.Thing1">
        <property name="thing2" ref="thing2" />
    </bean>
</beans>

FactoryBean 구현체에 <aop:scoped-proxy/>를 사용하면, FactoryBean 자체가 그 scope로 설정되는 것이지 getObject()를 통해서 반환되는 객체가 해당 scope로 설정되는 것이 아니다.