강의

멘토링

로드맵

Inflearn brand logo image

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

황인경님의 프로필 이미지
황인경

작성한 질문수

스프링 핵심 원리 - 기본편

autowired 해결이 안돼요..

작성

·

54

0


[질문 템플릿]
1. 강의 내용과 관련된 질문인가요? 예
2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? 예
3. 질문 잘하기 메뉴얼을 읽어보셨나요? 예

[질문 내용]
Autowired members must be defined in valid Spring bean (@Component|@Service|...) 라는 에러가 나왔습니다 코드 진행은 강의와 동일한 것 같아요..

 

package halo.core.scope;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.RequiredArgsConstructor;
import org.assertj.core.api.Assertions;
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 org.springframework.scheduling.annotation.Scheduled;

public class SingletonWithPrototypeTest1 {

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

        PrototypeBean prototypeBean2 = ac.getBean(PrototypeBean.class);
        prototypeBean2 = ac.getBean(PrototypeBean.class);
        prototypeBean2.addCount();
        Assertions.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();
        Assertions.assertThat(count1).isEqualTo(1);

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

    }

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



        @Autowired
        public ClientBean(PrototypeBean prototypeBean) {
            this.prototypeBean = prototypeBean;
        }

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

    @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" + this);
        }
    }
}

답변 1

0

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

황인경님께서 경험하고 계신 문제는 Autowired members must be defined in valid Spring bean (@Component|@Service|...) 오류 메시지로 인해 발생하는 것으로 보입니다. 이 오류는 @Autowired 어노테이션으로 주입하려는 의존성이 스프링 빈으로 제대로 등록되지 않았을 때 나타납니다.

스프링 컨테이너에 빈이 등록되려면 다음과 같은 몇 가지 사항을 확인해야 합니다:

  1. 클래스에 어노테이션 추가: @Autowired로 주입받는 객체(ClientBean, PrototypeBean)는 스프링의 빈 저장소 안에 등록되어야 합니다. 이를 위해 클래스에 @Component와 같은 어노테이션을 추가하여 스프링이 스캔할 수 있도록 합니다. 그러나 이번 코드는 AnnotationConfigApplicationContext를 통해 직접 클래스를 등록하고 있기 때문에, 사실 이 경우 어노테이션이 없어도 괜찮습니다.

  2. 빈 등록 확인: AnnotationConfigApplicationContext의 초기화 시, ClientBeanPrototypeBean을 명시적으로 파라미터로 넘겼습니다. 이 경우, 스프링은 해당 클래스들을 빈으로 등록합니다. 따라서 여기서 문제가 발생하는 것은 아니며, @Scope 어노테이션도 문제를 해결하지 못한 것 같습니다.

  3. 의존성 혹은 라이브러리 확인: 만약 ObjectProvider 대신 javax.inject.Provider를 사용해야 하는 상황이라면, 특정 버전의 javax.inject 라이브러리가 필요할 수 있습니다. 스프링 부트 3.0 이상을 사용 중인 경우, jakarta.inject:jakarta.inject-api:2.0.1을 의존성에 추가해주셔야 합니다.

이와 관련해서 유사한 문제를 겪은 사례를 찾아보니, 다른 학습자가 비슷한 문제를 논의하는 게시물이 있었습니다. 스프링빈 등록 및 의존성 해결과 관련해 자세히 설명되어 있습니다:

이 답변들이 문제 해결에 도움이 될 수 있을 것이라 생각합니다. 각각의 해결 방법을 읽어보시고, 해결되지 않는 부분이 있으면 추가적으로 질문 부탁드립니다.

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

황인경님의 프로필 이미지
황인경

작성한 질문수

질문하기