• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

9 - 프로토 타입 스코프를 싱글톤 빈과 함께 사용시 문제점 강의중 질문

23.11.18 21:04 작성 23.11.18 21:15 수정 조회수 157

1

질문 1. 아래코드에서 ClientBean이 내부 메서드에서 prototypeBean을 사용할 수 있는 이유?

static class ClientBean{ ... }의 코드에서는 스프링 빈으로 prototypeBean을 등록하는 부분이 없는데 어떻게 logic()메소드에서 prototypeBean.addCount();를 사용할 수 있는 것인가요?

 

🤔 제 생각에는 void singletonClientUsePrototype()의 코드인

AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(ClientBean.class, PrototypeBean.class); 

으로 빈으로 등록이 되는 것 같아서 코드를 다음과 같이 수정 후 실행해 보았습니다.

AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(ClientBean.class); 

👉 그러자 실행이 안되는 것을 확인 할 수 있었습니다.

 

질문 2. singletonClientUsePrototype()메소드에서 등록된 빈이 ClientBean에 어떻게 영향을 주는 것인가요?

🤔 ClientBean 코드의 ApplicationContext applicationContext;의 의존성 주입을 통해 이루어지는 것 같은데 이 코드에서는 어떤 것이 applicationContext에 해당되는 것인가요..? 따로 해당 인스턴스타입으로 등록된 빈이 없는 것 같은데 헷갈립니다ㅜㅜ

 

public class SingletonWithPrototypeTest1 {

  @Test
  void singletonClientUsePrototype(){
    AnnotationConfigApplicationContext ac =
            new AnnotationConfigApplicationContext(ClientBean.class, PrototypeBean.class);
    ClientBean client1 = ac.getBean(ClientBean.class);
    int count1 = client1.logic();
    assertThat(count1).isEqualTo(1);
    System.out.println("count1 = " + count1);

    ClientBean client2 = ac.getBean(ClientBean.class);
    int count2 = client2.logic();
    System.out.println("count2 = " + count2);
    assertThat(count2).isEqualTo(1);
  }

  @Scope("singleton")
  static class ClientBean {

    @Autowired
    ApplicationContext applicationContext;

    public int logic() {
      PrototypeBean prototypeBean = applicationContext.getBean(PrototypeBean.class);
      prototypeBean.addCount();
      return prototypeBean.getCount();
    }
  }



  @Scope("prototype")
  static class PrototypeBean {
    private int count = 0;

    public void addCount() {
      count++;
    }

    public int getCount() {
      return count;
    }

    @PostConstruct
    public void init() {
      System.out.println("PrototypeBean.init" + this);
    }

    @PreDestroy
    public void destroy() {
      System.out.println("PrototypeBean.destroy");
    }

  }
}

답변 1

답변을 작성해보세요.

0

인프런 질문

안녕하세요. 진서현님

1. ClientBean의 생상자를 보시면 @Autowired가 붙어있는 것을 확인할 수 있습니다. 이렇게 하면 ClientBean을 생성할 때 스프링 빈에 등록된 PrototypeBean도 함께 생성자에 전달하게 됩니다.

 

2. 다음 코드를 통해서 ApplicationContext applicationContext에 해당하는 스프링 컨테이너가 생성됩니다. 다음 코드의 부모 인터페이스가 바로 ApplicationContext applicationContext입니다.

AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(ClientBean.class, PrototypeBean.class);

 

그리고 다음 코드와 같이 @Autowired를 사용하게 되면 스프링 컨테이너 자신을 주입하게 됩니다.

@Scope("singleton")

static class ClientBean {

@Autowired

ApplicationContext applicationContext;

}

감사합니다.