SPRING

스프링 빈 스코프 (싱글톤, 프로토타입)

JUMP개발자 2020. 4. 12. 13:28

스프링 빈의 스코프는 크게 두가지로 나눌 수 있다.

- 싱글톤

- 프로토타입

 

일반적인 경우는 대부분 싱글톤 스코프로 빈을 참조하지만, 빈을 받아 올 때 마다 새로운 객체를 생성해야 하는 경우가 있을 수 있다. 그러할 경우에 프로토 타입 스코프를 이용한다.

 

아래와 같이 Single / Proto Type 클래스를 생성한다.

ProtoType으로 스코프를 생성하려면 아래 예시와 같이 @SCOPE 어노테이션을 사용한다.

proxyMode = ScopedProxyMode.TARGET_CLASS을 사용하는 이유는 PROTO 클래스 자체를 프로토 타입으로 지정하여, Single 클래스에서 Proto 빈을 호출하더라도 프로토타입 스코프로 빈을 참조하기 위해서이다. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 
import org.springframework.stereotype.Component;
 
@Component
public class Single {
 
    @Autowired
    Proto proto;
 
    public Proto getProto() {
        return proto;
    }
 
 
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

 

1
2
3
4
5
6
7
8
9
10
11
 
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;
 
@Component @Scope(value ="prototype", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class Proto {
 
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

 

아래와 같이 Sysout으로 찍어보면 Proto Type의 경우 매번 다른 객체가 생성되고, Singleton의 경우 같은 객체를 참조하는 것을 볼 수 있다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
 
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
 
@Component
public class AppRunner implements ApplicationRunner {
 
    /*
     * @Autowired Single single;
     * 
     * @Autowired Proto proto;
     */
    
    @Autowired
    ApplicationContext ctx;
    
    @Override
    public void run(ApplicationArguments args) throws Exception {
        // TODO Auto-generated method stub
        
        System.out.println("proto"); 
        
        System.out.println(ctx.getBean(Proto.class));
        System.out.println(ctx.getBean(Proto.class));
        System.out.println(ctx.getBean(Proto.class));
        
        System.out.println("single");
        
        System.out.println(ctx.getBean(Single.class));
        System.out.println(ctx.getBean(Single.class));
        System.out.println(ctx.getBean(Single.class));
        
        
        
    }
    
    
    
 
    
    
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

 

싱글톤, 프로토타입 호출 결과