작성
·
365
1
package hello.core.scope;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.inject.Provider;
import static org.assertj.core.api.Assertions.assertThat;
public class SingletonWithPrototypeTest2 {
@Test
void singletonClientUsePrototype() {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(ClientBean.class, PrototypeBean.class);
ClientBean clientBean1 = ac.getBean(ClientBean.class);
int count1 = clientBean1.logic();
assertThat(count1).isEqualTo(1);
ClientBean clientBean2 = ac.getBean(ClientBean.class, PrototypeBean.class);
int count2 = clientBean2.logic();
assertThat(count2).isEqualTo(1);
}
@Scope("singleton")
static class ClientBean {
@Autowired
private PrototypeBean prototypeBean;
public int logic() {
PrototypeBean prototypeBean1 = prototypeBean;
prototypeBean1.addCount();
int count = prototypeBean1.getCount();
return count;
}
}
@Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS)
static class PrototypeBean {
private int count = 0;
public void addCount() {
System.out.println("count = " + count + " : " + this);
count++;
}
public int getCount() {
System.out.println("count = " + count + " : " + this);
return count;
}
@PostConstruct
public void init() {
System.out.println("PrototypeBean.init " + this);
}
@PreDestroy
public void destroy() {
System.out.println("PrototypeBean.destroy");
}
}
}
1, ProxyMode를 사용했을 경우 addCount() 와 getCount() 호출 시 같은 PrototypeBean을 사용하게 할 순 없나요?
2. 위에서 addCount() 와 getCount() 호출 시 다른 PrototypeBean이 생성되는 이유가 무엇인가요?
감사합니다. 이해가됐어요!