inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

스프링 핵심 원리 - 기본편

6장 컴포넌트 스캔 - 필터

해결된 질문

126

전성민

작성한 질문수 4

1

안녕하세요.

강의자료-탐색 위치와 기본 스캔 대상 탐색할 패키지의 시작 위치 지정 문단에서

만약 지정하지 않으면 @ComponentScan이 붙은 설정 정보 클래스의 패키지가 시작 위치가 된다.

라고 읽었습니다

 

 

아래 코드에서 질문있습니다.(필터 문단 예제)

package hello.core.scan.filter;

import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;

public class ComponentFilterAppConfigTest {

    @Test
    void filterScan() {
        ApplicationContext ac = new AnnotationConfigApplicationContext(ComponentFilterAppConfig.class);

        BeanA beanA = ac.getBean("beanA", BeanA.class);
        Assertions.assertThat(beanA).isNotNull();
        org.junit.jupiter.api.Assertions.assertThrows(NoSuchBeanDefinitionException.class , ()->ac.getBean("beanB",BeanB.class));



    }






    @Configuration
    @ComponentScan(
            includeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION , classes = MyIncludeComponent.class),
            excludeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION , classes = MyExcludeComponent.class)
    )
    static class ComponentFilterAppConfig
    {

    }



}

위코드는 강사님이 써주신 코드와 일치하는 코드 입니다.

 

 

여기에서 @ComponentScan( includeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION , classes = MyIncludeComponent.class) 를 제외 했을때

 

즉 beanA를 포함 하는 코드를 지웠습니다.

 

그러면 아래와 같은 코드가 됩니다.

package hello.core.scan.filter;

import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;

public class ComponentFilterAppConfigTest {

    @Test
    void filterScan() {
        ApplicationContext ac = new AnnotationConfigApplicationContext(ComponentFilterAppConfig.class);

        BeanA beanA = ac.getBean("beanA", BeanA.class);
        Assertions.assertThat(beanA).isNotNull();
        org.junit.jupiter.api.Assertions.assertThrows(NoSuchBeanDefinitionException.class , ()->ac.getBean("beanB",BeanB.class));



    }






    @Configuration
    @ComponentScan(

            excludeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION , classes = MyExcludeComponent.class)
    )
    static class ComponentFilterAppConfig
    {

    }



}

 

위코드에서

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'beanA' available 에러가 발생하는 이유가 궁금합니다..

 

 

위 예제에서 @ComponentScan이 붙은 설정 정보 클래스와 beanA클래스는 같은 패키지 내에 있습니다.

 

@ComponentScan이 붙은 설정 정보 클래스의 패키지가 시작 위치가 됨으로

같은 패키지 내에 존재하는 BeanA클래스 객체는 스프링빈으로 등록되는거 아닌가요?

 

spring 객체지향

답변 1

1

OMG

안녕하세요. 전성민님, 공식 서포터즈 OMG입니다.

"ComponentScan의 includeFilter로 @MyIncludeComponent를 지정하여 스프링 빈으로 등록하겠다"

라는 속성을 사용하지 않는다면 아래와 같은 클래스는

@MyIncludeComponent 
Class BeanA {
}

빈껍데기의 의미없는 Class 그 자체일뿐입니다.

Class BeanA {
}

 

왜냐하면 @MyIncludeComponent는 스프링과 전혀 무관하고

단순 주석과 같은 어노테이션일 뿐,

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyIncludeComponent

컴포넌트스캔에 어떠한 동작을 하도록 명령하지 않는다면 스프링 빈으로 등록될 이유가 없기 때문입니다.

 

만약 지정하지 않으면 @ComponentScan이 붙은 설정 정보 클래스의 패키지가 시작 위치가 된다.

이 내용이 이해하신 내용을 바탕으로 성립하려면

이렇게 아무 의미없는 클래스 들도 모두 스프링 빈으로 등록하겠다라는 뜻이 됩니다.

package hello.scan.core.filter;
Class BeanC {
}
package hello.scan.core.filter;
Class 아무클래스 {
}

 

감사합니다.

0

전성민

감사합니다!

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

0

49

2

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

0

72

1

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

0

87

1

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

0

79

1

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

0

75

1

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

0

116

2

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

0

81

1

provider 사용하는 이유

0

85

1

다음 강의 뭘 들어야 할까요

0

123

2

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

0

62

1

beanB

0

79

2

퀴즈다시풀기

0

63

1

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

0

90

2

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

0

63

3

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

0

102

2

도메인의 정의?

0

57

1

ApplicationContext 질문입니다.

0

60

1

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

0

86

2

ai api 선정하기 관련 질문

0

115

2

생성자 자동주입 관련해서

0

60

1

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

0

93

2

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

1

63

1

12:25

0

75

2

appConfig.xml 오류

0

127

1