IoC 컨테이너 - Bean 의 스코프(Scope)
- 📚 Spring/Spring 개념
- 2020. 9. 9. 11:37
스코프
싱글톤
프로토타입
- Request
- Session
- WebSocket ...
싱글톤 객체 사용주 주의 사항
프로퍼티가 공유된다는 것을 알아야 한다. 즉, 쓰레드 세이프티 하게 코딩해야 한다.
ApplicationContext 만들 때 생성되기 때문에 애플리케이션 구동시 시간이 걸릴 수 있다.
1. 싱글톤과 프로토타입
package org.kyhslam;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component @Scope("prototype")
public class Proto {
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Single {
@Autowired
private Proto proto;
public Proto getProto() {
return proto;
}
}
@Component
public class AppRunner implements ApplicationRunner {
@Autowired
ApplicationContext ctx;
@Override
public void run(ApplicationArguments args) throws Exception {
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));
}
}
위의 코드를 실행하면 Proto는 매번 다른 인스턴스를 가져오는 것을 볼 수 있다.
proto
org.kyhslam.Proto@27f3b6d6
org.kyhslam.Proto@757f675c
org.kyhslam.Proto@2617f816
single
org.kyhslam.Single@676f0a60
org.kyhslam.Single@676f0a60
org.kyhslam.Single@676f0a60
2. 싱글톤에 의존한 프로토타입 가져오기
프로토타입의 빈이 싱글톤을 참조할 때는 아무런 문제가 없다.
그러나 싱글톤 빈이 프로토타입 빈을 참조할 때는 문제가 있다.
즉, 싱글톤에 의존하는 프로토타입이 마치 싱글톤처럼 작동하고 있다.
해당 문제를 소스로 재현해보면
System.out.println("proto by single");
System.out.println(ctx.getBean(Single.class).getProto());
System.out.println(ctx.getBean(Single.class).getProto());
System.out.println(ctx.getBean(Single.class).getProto());
proto by single
org.kyhslam.Proto@a68df9
org.kyhslam.Proto@a68df9
org.kyhslam.Proto@a68df9
싱글톤 빈이 프로토타입을 가져온 걸 보면 바뀌지 않는다. 즉, 싱글톤 같다.
3. 싱글톤에 의존하는 프로토타입 문제 해결 방법
아랯럼 Proto에 proxyMode를 설정하자.
package org.kyhslam;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;
@Component @Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class Proto {
}
그리고 다시 구동해보면 싱글톤에서 참조하는 프로토타입도 매번 변경되는 것을 볼 수 있다.
System.out.println("proto by single");
System.out.println(ctx.getBean(Single.class).getProto());
System.out.println(ctx.getBean(Single.class).getProto());
System.out.println(ctx.getBean(Single.class).getProto());
proto by single
org.kyhslam.Proto@238ad8c
org.kyhslam.Proto@430fa4ef
org.kyhslam.Proto@1761de10
원리는 proty패턴이다.
본래는 싱글톤 -> 프로토타입 관겨였으나 proxy가 관리하여 싱글톤 -> 프록시 -> 프로토타입 관계로 빠귄것이다.
싱글톤이 스프링에 의해 생성된 proxy를 참조하고 proxy는 매번 다른 프로토타입을 생성하여 반환한다.
'📚 Spring > Spring 개념' 카테고리의 다른 글
IoC Container - MessageSource (0) | 2020.09.11 |
---|---|
IoC 컨테이너 - Environment (0) | 2020.09.09 |
@Component와 Component Scan (0) | 2020.09.01 |
@Autowire (0) | 2020.08.31 |
@NoArgsConstructor (0) | 2020.08.24 |