필터
- includeFilters: 컴포넌트 스캔할 대상을 추가로 지정
- excludeFilters: 컴포넌트 스캔에서 제외할 대상을 지정
@MyIncludeComponent
package hello.core.scan.filter;
import java.lang.annotation.*;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyIncludeComponent {
}
@MyExcludeComponent
package hello.core.scan.filter;
import java.lang.annotation.*;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyExcludeComponent {
}
BeanA.java
package hello.core.scan.filter;
@MyIncludeComponent
public class BeanA {
}
BeanB.java
package hello.core.scan.filter;
@MyExcludeComponent
public class BeanB {
}
ComponentFilterAppConfigTest.java
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;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.springframework.context.annotation.ComponentScan.*;
public class ComponentFilterAppConfigTest {
@Test
void filterScan(){
ApplicationContext ac = new AnnotationConfigApplicationContext(ComponentFilterAppConfig.class);
BeanA beanA = ac.getBean("beanA",BeanA.class); //스프링 빈은 처음 문자가 소문자
assertThat(beanA).isNotNull();
assertThrows(NoSuchBeanDefinitionException.class,
()->ac.getBean("beanB", BeanB.class));
}
@Configuration
@ComponentScan(
//includeFilters는 컴포넌트 스캔 대상을 추가로 지정
includeFilters = @Filter(type = FilterType.ANNOTATION, classes = MyIncludeComponent.class),
//excludeFilters는 컴포넌트 스캔 대상에서 제외
excludeFilters = @Filter(type = FilterType.ANNOTATION, classes = MyExcludeComponent.class)
)
static class ComponentFilterAppConfig{
}
}
includeFilters 에 MyIncludeComponent 애노테이션을 추가해서 BeanA가 스프링 빈에 등록된다.
excludeFilters 에 MyExcludeComponent 애노테이션을 추가해서 BeanB는 스프링 빈에 등록되지 않는다.
FilterType 옵션 FilterType은 5가지 옵션이 있다.
- ANNOTATION: 기본값, 애노테이션을 인식해서 동작한다. ex) org.example.SomeAnnotation
- ASSIGNABLE_TYPE: 지정한 타입과 자식 타입을 인식해서 동작한다. ex) org.example.SomeClass
- ASPECTJ: AspectJ 패턴 사용 ex) org.example..*Service+
- REGEX: 정규 표현식 ex) org\.example\.Default.*
- CUSTOM: TypeFilter 이라는 인터페이스를 구현해서 처리 ex) org.example.MyTypeFilter
'Spring' 카테고리의 다른 글
Spring- 옵션 선택 (0) | 2023.01.29 |
---|---|
Spring- 의존관계 자동 주입 (0) | 2023.01.29 |
Spring- 컴포넌트 스캔과 자동 의존관계 주입 (0) | 2023.01.26 |
Spring- @configuration과 싱글톤 (0) | 2023.01.24 |
Spring- 싱글톤 (0) | 2023.01.24 |