컴포넌트 스캔 - 필터
2023. 7. 17. 21:39ㆍSpring/[inflearn]스프링 핵심 원리 - 기본편
◎ 필터
-> 필터를 통해 컴포넌트 스캔 대상에서 추가 및 제거를 할 수 있다.
-> includeFilters : 컴포넌트 스캔 대상을 추가로 지정한다.
-> excludeFilters : 컴포넌트 스캔에서 제외할 대상을 지정한다.
-> 컴포넌트 스캔 대상에 추가할 애너테이션
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyIncludeComponent {
}
-> 컴포넌트 스캔 대상에서 제외할 애너테이션
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyExcludeComponent {
}
-> 컴포넌트 스캔 대상에 추가할 클래스
@MyIncludeComponent
public class BeanA {
}
-> 컴포넌트 스캔 대상에서 제외할 클래스
@MyExcludeComponent
public class BeanB {
}
-> 전체 테스트
public class ComponentFilterAppConfigTest {
@Test
void filterScan(){
AnnotationConfigApplicationContext 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에는 MyIncludeCompoent를 지정하여 컴포넌트 스캔 대상에 추가하였고, excludeFitler에는 MyExcludeComponent를 지정하여 컴포넌트 스캔 대상에서 제외하였다.
- 따라서 beanA라는 스프링 빈을 찾으면 찾아지고, beanB라는 스프링 빈을 찾으면 컴포넌트 스캔 대상에 제외되었기 때문에 해당 빈을 찾을 수 없어 NoSuchBeanDefinitionException이 발생한다.
◎ FilterType 옵션
-> ANNOTATION : 기본값으로 애너테이션을 인식해서 동작한다.
-> ASSIGNABLE_TYPE : 지정한 타입과 자식 타입을 인식해서 동작한다.
-> ASPECTJ : AspectJ 패턴 사용
-> REGEX : 정규 표현식
-> CUSTOM : TypeFilter라는 인터페이스를 구현해서 처리
☆ 참고
'Spring > [inflearn]스프링 핵심 원리 - 기본편' 카테고리의 다른 글
의존관계 자동 주입 (0) | 2023.07.18 |
---|---|
컴포넌트 스캔 - 중복 등록과 충돌 (0) | 2023.07.17 |
컴포넌트 스캔 - 탐색 위치 & 기본 스캔 대상 (0) | 2023.07.17 |
컴포넌트 스캔 - 컴포넌트 스캔 & 의존관계 자동 주입 (0) | 2023.07.17 |
@Configuration & 싱글톤 (0) | 2023.07.14 |