inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

스프링 핵심 원리 - 기본편

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

테스트 실패: Unsatisfied dependency expressed through field 'prototypeBeanProvider'

1349

4562sky

작성한 질문수 5

2

해당 오류입니다.

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'singletonWithPrototypeTest1.ClientBean': Unsatisfied dependency expressed through field 'prototypeBeanProvider': No qualifying bean of type 'javax.inject.Provider<hello.core.scope.SingletonWithPrototypeTest1$PrototypeBean>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

 

빈 주입이 안되어 오류가 나는 것 같아 @ComponentScan도 달아봤습니다. 빈을 못찾는다고 할까요

package hello.core.scope;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.inject.Provider;

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

@ComponentScan
public class SingletonWithPrototypeTest1 {

@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 singletonClientUserPrototype(){
// 스프링 컨텍스트를 생성하고 빈을 가져옴
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);
// 같은 count가 증가함
}

@Scope("singleton")
@Component
static class ClientBean{

// ObjectProvider를 통해 싱글톤 빈과 프로토타입을 함께 사용가능
@Autowired
private Provider<PrototypeBean> prototypeBeanProvider;

public int logic(){
PrototypeBean prototypeBean = prototypeBeanProvider.get();
prototypeBean.addCount();
int count = prototypeBean.getCount();
return count;
}
}

@Scope("prototype")
@Component
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" + this);
}
}
}

 

spring 객체지향

답변 2

2

OMG

안녕하세요. 4562sky님, 공식 서포터즈 OMG입니다.

다음 링크의 영한님 답변을 참고해주세요 😀

해결이 안될 경우 댓글 남겨주세요 ^^

https://www.inflearn.com/questions/722428/javax-inject-provider-%EC%A3%BC%EC%9E%85-%EC%A7%88%EB%AC%B8

감사합니다.

0

인프런 AI 인턴

안녕하세요, 인프런 AI 인턴입니다.

4562sky님께서 겪고 계신 org.springframework.beans.factory.UnsatisfiedDependencyException 오류는 스프링이 ClientBean 클래스의 의존성을 충족시킬 수 있는 PrototypeBean 타입의 빈을 찾지 못해 발생하는 문제입니다. 이러한 문제는 종종 빈의 스코프 설정, 컴포넌트 스캔 방식 또는 javax.inject.Provider 사용 방식에 문제가 있을 때 발생합니다.

질문하신 내용과 관련하여, 다음과 같은 제안을 드리고자 합니다.

  1. Provider 사용법 확인: 질문에서 언급하신 오류는 스프링이 PrototypeBean의 Provider를 찾지 못하는 상황에서 발생합니다. 이 경우, PrototypeBean을 올바르게 정의하고 선언한 것인지 확인해야 합니다. 특히 Provider<PrototypeBean>을 이용하여 프로토타입 빈을 주입받을 때, 이를 올바르게 구성함으로써 라이프사이클 이슈를 해결할 수 있습니다.

  2. @ComponentScan 범위 확인: @ComponentScan을 사용할 때 스캔 범위 내에 ClientBeanPrototypeBean이 올바르게 포함되어 있는지 확인해야 합니다. 스캔 범위를 제대로 설정하지 않으면 스프링 컨테이너가 이들 빈을 찾지 못해 위와 같은 오류가 발생할 수 있습니다.

  3. 빈 정의 및 주입 방식 확인: Provider<PrototypeBean>를 사용할 때 PrototypeBean이 스프링 컨텍스트에 올바르게 등록되어 있어야 합니다. @Component, @Scope 어노테이션을 사용하여 빈 정의를 명확히 하고, 이를 통해 주입받으려는 빈이 스프링에 의해 관리되고 있는지 확인하는 것이 중요합니다.

이와 관련해서 도움이 될 수 있는 이전 질문의 답변을 찾았습니다. 이 답변은 Provider 사용법과 관련된 문제를 해결하는 데 도움을 줄 수 있습니다:

  • “Provider 에러관련해서 질문있어요”에서는 비슷한 상황에 있던 다른 학습자의 질문과, 그에 대한 코멘트를 찾아볼 수 있습니다. 이 코멘트에서는 javax.inject:javax.inject:1 라이브러리 추가 후 오류가 발생하는 상황을 다루고 있으며, 이는 4562sky님의 상황과 유사할 수 있습니다.

각 답변에서는 오류 해결을 위한 다양한 접근 방식을 소개하고 있으므로, 이를 참고하여 문제를 해결하시는 데 도움이 되기를 바랍니다.

저는 질문자님의 이해를 돕고자 지식공유자님의 기존 답변을 참고하여 유사한 답변 링크를 추천해드리고 있습니다.
현재 베타 기능으로 답변이 만족스럽지 않을 수 있는 점 양해 부탁드립니다. 🙏
추가적으로 궁금한 점이 있으시면, 이어서 질문해 주세요. 곧 지식공유자께서 답변해 주실 것입니다.

코드 자료

0

40

2

구현체가 동적으로 정해질 때, 팩토리 기법을 사용하나요?

0

52

2

MemberService의 인터페이스를 왜 사용하는지 궁금합니다.

0

75

1

롬복 @Setter를 써야 하는 상황이 있는건가요?

0

89

1

빈 등록 메서드의 파라미터가 빈이 아니어도 되나요?

0

81

1

테스트 속도가 나중에 영향이 있을까요?

0

77

1

gradle 설정 안떠서 질문 남깁니다!

0

121

2

build.gradle로 프로젝트를 여는 이유

0

85

1

provider 사용하는 이유

0

89

1

다음 강의 뭘 들어야 할까요

0

126

2

프로토타입 빈, 직접 destroy 호출 안 할 경우

0

64

1

beanB

0

82

2

퀴즈다시풀기

0

68

1

Gradle로 바꿔도 오류가 똑같이 발생하네요 ㅠㅠ

0

92

2

"중복 등록과 충돌" 강의에서 강사님과 다른 에러가 발생합니다.

0

67

3

run 실행했는데 결과창이 이렇게 뜨네요 왜 그런건가요>

0

106

2

도메인의 정의?

0

59

1

ApplicationContext 질문입니다.

0

63

1

@Scope의 proxyMode를 사용할때 단위 테스트 방법

0

88

2

ai api 선정하기 관련 질문

0

118

2

생성자 자동주입 관련해서

0

65

1

생성자 직접 호출 vs 팩토리 메서드 패턴

0

97

2

Spring에서 SessionScope와 RequestScope는 함께 사용되나요?

1

65

1

12:25

0

78

2