어노테이션 상속

상훈·2024년 2월 1일
  • AutoAppConfig를 만들어서 스프링 컨테이너에 빈을 등록하기 위해서는 탐색 범위를 지정해주는 @ComponentScan이 필수적

  • ComponentScan 어노테이션을 @SpringBootApplication도 갖고 있기 때문에 스프링 부트를 쓰면 스프링 빈을 등록할 수 있다고 함

궁금점

  • @SpringBootApplication이 탐색 범위에 대한 어노케이션도 갖고 있다면 @ComponentScan 대신 @SpringBootApplication을 사용할 수 있지 않을까?
package hello.core;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;

@Configuration
//@ComponentScan(
//        excludeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Configuration.class)
//)
@SpringBootApplication
public class AutoAppConfig {

}

테스트

  • org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'hello.core.member.MemberService' available: expected single matching bean but found 2: memberServiceImpl,memberService 에러 발생
  • image-20240127230203474

ComponentScan Annotation을 상속해서 사용한 것이 불가능한가?

  • TestAnnotation을 만들어 테스트 진행

  • // TestAnnotation 생성
    package hello.core.annotation;
    
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.FilterType;
    
    import java.lang.annotation.*;
    
    @Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Inherited
    @Documented
    @Qualifier("TestAnnotation")
    @ComponentScan(
            excludeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Configuration.class)
    )
    public @interface TestAnnotation {
    }
    
  • package hello.core;
    
    import hello.core.annotation.TestAnnotation;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.FilterType;
    
    //@Configuration
    //@ComponentScan(
    //        excludeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Configuration.class)
    //)
    //@SpringBootApplication
    @TestAnnotation
    @Configuration
    public class AutoAppConfig {
    
    }
  • 결과 (정상 작동)

image-20240128105509652

profile
문송 개발자

0개의 댓글