• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

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

24.05.03 13:17 작성 조회수 99

0

해당 오류입니다.

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);
}
}
}

 

답변 2

·

답변을 작성해보세요.

0

OMG님의 프로필

OMG

2024.05.04

안녕하세요. 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 인턴

2024.05.03

안녕하세요, 인프런 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님의 상황과 유사할 수 있습니다.

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

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