(Spring) Singleton, Prototype
Spring
06/17/2021
μ€νλ§ λΉ μ€μ½ν
μ€λΈμ νΈκ° μμ±λκ³ , μ μ©λλ λ²μλ₯Ό λΉμ μ€μ½ν(Scope)λΌκ³ νλ€.
μ€νλ§ λΉμ κΈ°λ³Έ μ€μ½νλ μ±κΈν€μ΄λ€.
μ±κΈν€ μ€μ½νλ κ°μ μ κ±°νμ§ μλ ν μ€νλ§ μ»¨ν μ΄λκ° μ‘΄μ¬νλ λμ κ³μ μ μ§λλ€.
κ²½μ°μλ°λΌμ μ±ν΄ν€ μΈμ μ€μ½νλ₯Ό κ°μ§ μ μλ€.
- νλ‘ν νμ μ€μ½ν
- μμ² μ€μ½ν
- μΈμ μ€μ½ν
λ±λ±...
μ΄ μ€ μ€νλ§μμμ μ±κΈν€κ³Ό νλ‘ν νμ μ λν΄μ μμ보μ.
π©βπ» Singleton
- μ€νλ§ μ»¨ν μ΄λμ μμκ³Ό μ’ λ£κΉμ§ 1κ°μ κ°μ²΄λ‘ μ μ§λ¨
- μ€νλ§μ ν΅ν΄μ beanμ μ 곡λ°μΌλ©΄ μΈμ λ μ£Όμ λ°μ beanμ λμΌν κ°μ²΄λΌλ κ°μ νμμ κ°λ°μ νλ€.
π©βπ» Prototype
λΉμ μ£Όμ λ°μ λλ§λ€ λ§€λ² μλ‘μ΄ μΈμ€ν΄μ€λ₯Ό λ§λ€μ΄μ μ¬μ©
@Component @Scope("prototype")public class Proto {}
@Componentpublic 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));// μ 보 κ°μ }}
π©βπ» μ€μ½νμ νΌμ©
νλ‘ν νμ μμ μ±κΈν€ λΉμ μ°Έμ‘°ν κ²½μ°
β νλ‘ν νμ μ λΉμ λ§€λ² μλ‘ μμ±λλ λ°λ©΄, μ±κΈν€ κ°μ²΄λ μΈμ λ λμΌνλ€.
@Component @Scope("prototype")public class Proto { @Autowired Single single;}
μ±κΈν€ λΉμ΄ νλ‘ν νμ λΉμ μ°Έμ‘°ν κ²½μ°
@Componentpublic class Single {
@Autowired Proto proto;
public Proto getProto() { return proto; }}
@Componentpublic class AppRunner implements ApplicationRunner {
@Autowired ApplicationContext ctx;
@Override public void run(ApplicationArguments args) throws Exception { 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()); }}
β μ±κΈν€ λΉ μΈμ€ν΄μ€κ° νλ² λ§λ€μ΄μ§κ³ , μ΄ λ νλ‘ν νμ μ λΉ μΈμ€ν΄μ€μ νλ‘νΌν°λ μΈν μ΄ λλ€.
μ΄ λ μ±κΈν€ λΉμ λ§€λ² νΈμΆν λλ§λ€ νλ‘ν νμ μ λΉλ μ²μμ μΈν λ μΈμ€ν΄μ€λ‘ κ³ μ μ΄ λλ€.
π‘ νν λ‘νμ μ μΈμ€ν΄μ€κ° μ μμ μΌλ‘ μμ±λκ² νλ €λ©΄ ?
β proxyMode μ€μ
@Component @Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS)public class Proto { @Autowired Single single;}
- DEFAULT : νλ‘μ μ¬μ© μν¨
- TARGET_CLASS : λ€μ΄λλ―Ή νλ‘μ μ μ©
- INTERFACES : μΈμ€ν΄μ€ νλ‘μ μμ±
μΆμ² - https://blossun.github.io/spring/core-technology/01_IoC-컨ν μ΄λμ-λΉ_05/
- (Spring) μ€νλ§μ΄ λΉ μ€μ½νλ₯Ό μ±ν΄ν€μΌλ‘ λ§λλ μ΄μ
- μ νμ λ ¬/λ²λΈμ λ ¬/μ½μ μ λ ¬