• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

해당 proxymode 를 프로토타입쪽에 적용해보았는데 실패합니다.

22.03.27 21:58 작성 조회수 209

0

안녕하세요 아래와같이 prototype bean 에대해서 proxy mode 를 적용했는데.. 테스트 결과가실패하네요. 보면 prototype 이 제대로 만들어지지 않는거같은데 ComponentScan 으로 만든게아닌 임의의 AnnotationApplicationContext 를통해서 만들어서 그런가요??

 

    @Test
    void prototypeFInd() {
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(PrototypeBean.class);
        PrototypeBean bean = ac.getBean(PrototypeBean.class);
        bean.addCount();
        Assertions.assertThat(bean.getCount()).isEqualTo(1);

        PrototypeBean bean2 = ac.getBean(PrototypeBean.class);
        bean2.addCount();
        Assertions.assertThat(bean2.getCount()).isEqualTo(1);
    }


    @Test
    void singletonCLientUsePrototype() {
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(ClientBean.class, PrototypeBean.class);

        ClientBean clientBean1 = ac.getBean(ClientBean.class);
        int count1 = clientBean1.logic();
        Assertions.assertThat(count1).isEqualTo(1);

        ClientBean clientBean2 = ac.getBean(ClientBean.class);
        int count2 = clientBean2.logic();
        Assertions.assertThat(count2).isEqualTo(1);
    }

    @Scope("singleton")
    @RequiredArgsConstructor
    static class ClientBean {
        private final PrototypeBean prototypeBean;

        public int logic() {
            System.out.println("prototypeBean Add = " + prototypeBean);
            prototypeBean.addCount();
            return prototypeBean.getCount();
        }
    }

    @Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS)
    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");
        }
    }

답변 2

·

답변을 작성해보세요.

1

안녕하세요. 스프링님

전체 프로젝트를 압축해서 구글 드라이브로 공유해서 링크를 남겨주세요.

구글 드라이브 업로드 방법은 다음을 참고해주세요.

https://bit.ly/3fX6ygx

 

주의: 업로드시 링크에 있는 권한 문제 꼭 확인해주세요

 

추가로 다음 내용도 코멘트 부탁드립니다.

1. 실행 방법을 알려주세요.

2. 어떻게 문제를 확인할 수 있는지 자세한 설명을 남겨주세요.

감사합니다.

 

0

BBIRA님의 프로필

BBIRA

2024.03.12

스프링 컨테이너에는 가짜 프록시 객체만 있습니다. 현재 변수 bean에는 가짜 프록시 객체가 할당되었습니다. 가짜 프록시 객체에서 메서드를 호출할 때마다 가짜 프록시 객체는 내부에서 실제 빈을 요청하게 됩니다. 이 객체는 프로토타입 빈이므로 매번 새로운 인스턴스를 반환하게 됩니다. - 제 생각입니다. ㅎ