Spring Non Singletone

Spring Non Singletone 객체생성


Spring에서 정의된 bean은 기본적(default)으로 Singletone으로 관리된다. 하지만 어플리케이션에 따라 Singletone으로 객체를 관리하는 것이 아니라 어떤 bean 새롭게 인스턴스를 생성해야 하는 경우가 있다. 이때 사용되는 방법이 scope를 직접지정하는 방법이다.
  • Xml Scope 지정방법

1
<bean id = "someBean" class = "com.SomeBean" scope="prototype"/>
cs

위와 같이 xml파일 bean 정의시 scope를 prototype으로 추가하여 정의한다. 기본값은 singletone이다.

  • Annotation Scope 지정방법

1
2
3
4
5
@Scope("prototype")
@Service("someBean")
public class SomeBean {
 
}
cs

Annontation bean 정의시 @Scope("prototype")을 추가하여 정의한다.

위와 같이 정의하여 Application Context는 getBean("someBean")을 호출시 매번 새로운 인스턴스를 생성하여 리턴하게 된다.

  • Test
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.ljs;
 
import org.springframework.context.support.GenericXmlApplicationContext;
 
public class ApplicationMain {
 
    public static void main(String[] args) {
        // ApplicationContext 부트스트랩
        GenericXmlApplicationContext appCtx = new GenericXmlApplicationContext();
        appCtx.load("classpath:META-INF/spring/app-context.xml");
        appCtx.refresh();
        
        SomeBean someBean1 = (SomeBean) appCtx.getBean("someBean");
        SomeBean someBean2 = (SomeBean) appCtx.getBean("someBean");
        
        System.out.println(someBean1 == someBean2);
        
        appCtx.close();
    }
}
cs

<수행결과>
someBean1 == someBean2 ? false

위에 정의된 bean설정에서 scope="prototype"/ @Scope("prototype")을 제거하거나 "singletone"으로 변경시 수행결과는 true가 된다.
Spring에서 SingleTone이 아닌 Non Single Tone으로 객체를 참조 할 수 있게 된다.

하지만 여기서 파생되는 문제가 있다. 만약 SingleTone으로 생성된 객체가 protytype로 지정된 객체를 주입 받는 경우는 어떨까? 정답은 prototype은 무시되고 주입받은 객체역시 SingleTone처럼 동작하게 된다. 왜냐하면 SingleTone객체는 처음에 한 번 생성되고, 내부 property에 Non SingleTone객체를 계속 참조하고 있기 때문에 Bean이 메모리에서 소멸되지 않기 때문이다.

그렇다고 getter에서 New Instatnce로 Bean을 새롭게 생성하는 경우는 이미 IoC패턴과 무관한 이야기가 된다. 그래서 사용하는 방법이 Method LookUp Injection이다. (잘 쓰이지는 않는단다.) 아래 링크를 참조.

다운로드


이 글을 공유하기

댓글

Email by JB FACTORY