-
스프링 빈 스코프 (싱글톤, 프로토타입)SPRING 2020. 4. 12. 13:28
스프링 빈의 스코프는 크게 두가지로 나눌 수 있다.
- 싱글톤
- 프로토타입
일반적인 경우는 대부분 싱글톤 스코프로 빈을 참조하지만, 빈을 받아 올 때 마다 새로운 객체를 생성해야 하는 경우가 있을 수 있다. 그러할 경우에 프로토 타입 스코프를 이용한다.
아래와 같이 Single / Proto Type 클래스를 생성한다.
ProtoType으로 스코프를 생성하려면 아래 예시와 같이 @SCOPE 어노테이션을 사용한다.
proxyMode = ScopedProxyMode.TARGET_CLASS을 사용하는 이유는 PROTO 클래스 자체를 프로토 타입으로 지정하여, Single 클래스에서 Proto 빈을 호출하더라도 프로토타입 스코프로 빈을 참조하기 위해서이다.
123456789101112131415161718package com.example.demo;import org.springframework.stereotype.Component;@Componentpublic class Single {@AutowiredProto proto;public Proto getProto() {return proto;}}http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter1234567891011package com.example.demo;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의 경우 같은 객체를 참조하는 것을 볼 수 있다.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647package com.example.demo;import org.springframework.context.ApplicationContext;import org.springframework.stereotype.Component;@Componentpublic class AppRunner implements ApplicationRunner {/** @Autowired Single single;** @Autowired Proto proto;*/@AutowiredApplicationContext ctx;@Overridepublic void run(ApplicationArguments args) throws Exception {// TODO Auto-generated method stubSystem.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싱글톤, 프로토타입 호출 결과 'SPRING' 카테고리의 다른 글
스프링 Properties 관련 정리 (0) 2020.04.15 스프링 프로파일 (Profile) (0) 2020.04.14 Component와 ComponentScan 정리 (0) 2020.04.10 @Autowired 심화 학습(자료 : 백기선) (0) 2020.04.06 AOP (Aspect Oriented Programming) (자료: 백기선) (0) 2020.03.23