스코프
- 싱글톤
- 프로토타입 (Request, Session, WebSocket ... 등)
Proto.java
@Component
@Scope(value = "prototype")
// @Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class Proto {
@Autowired
Single single;
}
Single.java
@Component
public class Single {
@Autowired
Proto proto;
public Proto getProto() {
return proto;
}
// @Autowired
// private ObjectProvider<Proto> proto;
//
// public Proto getProto() {
// return proto.getIfAvailable();
// }
}
AppRunner.java
@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));
}
}
위의 결과와 같이 싱글톤은 유일한 인스턴스를 제공하고 프로토타입 참조할 때마다 새로운 인스턴스를 생성한다.
대부분의 개발자들이 싱글톤을 제외하고 프로토타입을 사용하는 경우는 거의 없을 것이다. 싱글톤의 특징 정도만 이해하고 가면 된다.
싱글톤 특징
- 싱글톤은 멀티 쓰레드 환경에서는 프로퍼티를 공유하기 때문에 Thread-safe 하지 못하다. 하지만 대부분 스프링에는 안전장치가 마련되어 있다.
- 싱글톤은 하나의 인스턴스만 생성하기 떄문에 메모리 누수를 방지한다.
그 밖에 싱글톤 빈이 프로토타입 빈을 참조하기 위해서는 scoped-proxy, Object-Provider를 사용하면된다.
위의 소스에 주석으로 표시했다.
'BackEnd > Spring' 카테고리의 다른 글
[Spring] 스프링(Spring) 핵심 기술 이야기 3부 - @Component와 컴포넌트 스캔 (0) | 2020.10.07 |
---|---|
[Spring] 스프링(Spring) 핵심 기술 이야기 2부 - @Autowire (0) | 2020.09.16 |
[Spring] 스프링(Spring) 핵심 기술 이야기 1부 - IoC (0) | 2020.09.10 |
댓글