인프런 커뮤니티 질문&답변

coli님의 프로필 이미지

작성한 질문수

스프링 핵심 원리 - 기본편

프로토타입 스코프 - 싱글톤 빈과 함께 사용시 Provider로 문제 해결

생성자 주입으로 변경했을 때 Provider 생성할때 오류

23.02.19 14:55 작성

·

1.2K

0

학습하는 분들께 도움이 되고, 더 좋은 답변을 드릴 수 있도록 질문전에 다음을 꼭 확인해주세요.

1. 강의 내용과 관련된 질문을 남겨주세요.
2. 인프런의 질문 게시판과 자주 하는 질문(링크)을 먼저 확인해주세요.
(자주 하는 질문 링크: https://bit.ly/3fX6ygx)
3. 질문 잘하기 메뉴얼(링크)을 먼저 읽어주세요.
(질문 잘하기 메뉴얼 링크: https://bit.ly/2UfeqCG)

질문 시에는 위 내용은 삭제하고 다음 내용을 남겨주세요.
=========================================
[질문 템플릿]
1. 강의 내용과 관련된 질문인가요? (예/아니오)
2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예/아니오)
3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예/아니오)

[질문 내용]
여기에 질문 내용을 남겨주세요.

단위 테스트로 할 때 필드 주입이 좋지 않다고 하셔서 생성자 주입으로 변경 후 돌려봤을 때 Provider를 적용하기 전에 ObjectProvider<PrototypeBean> 으로 했을 때는 테스트가 성공했지만 Provider로 할때는 다음과 같은 에러가 나서 왜 발생했는지 질문드립니다

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'singletonWithPrototype.ClientBean': Unsatisfied dependency expressed through constructor parameter 1: No qualifying bean of type 'javax.inject.Provider<hello.core.scope.SingletonWithPrototype$PrototypeBean>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

아래는 전체 코드 입니다.

package hello.core.scope;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
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 javax.inject.Provider;

import static org.assertj.core.api.Assertions.assertThat;

public class SingletonWithPrototype {

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

        PrototypeBean prototypeBean2 = ac.getBean(PrototypeBean.class);
        prototypeBean2.addCount();
        assertThat(prototypeBean2.getCount()).isEqualTo(1);
    }
    
    @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);
        int count2 = clientBean2.logic();
        assertThat(count2).isEqualTo(1);
    }

    @Scope("singleton")
    static class ClientBean {
        private final PrototypeBean prototypeBean; //생성시점에 주입되어서 계속 같은 거 사용.
        private final Provider<PrototypeBean> prototypeBeanProvider;

        @Autowired //생성자 하나니까 @Autowired 생략해도 되긴 함
        public ClientBean(PrototypeBean prototypeBean, Provider<PrototypeBean> prototypeBeanProvider) {
            this.prototypeBean = prototypeBean;
            this.prototypeBeanProvider = prototypeBeanProvider;
        }

        public int logic() {
            PrototypeBean prototypeBean = prototypeBeanProvider.get();
            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");
        }
    }
}

답변 2

4

윤승제님의 프로필 이미지

2024. 02. 26. 21:19

스프링부트 3.0 이상일 때는 javax.inject:javax.inject:1 대신 jakarta.inject:jakarta.inject-api:2.0.1를 gradle에 추가해주셔야 실행됩니다

0

김영한님의 프로필 이미지
김영한
지식공유자

2023. 02. 24. 21:13

안녕하세요. 호룰루님

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

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

https://bit.ly/3fX6ygx

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

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

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

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

감사합니다.

 

coli님의 프로필 이미지

작성한 질문수

질문하기