이번에는 필터에 대해 알아보았다.

 

 includeFilters : 컴포넌트 스캔 대상을 추가로 지정한다.

excludeFilters : 컴포넌트 스캔에서 제외할 대상을 지정한다.

 

package hello.core.scan.filter;

import java.lang.annotation.*;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyIncludeComponent {
}
package hello.core.scan.filter;

import java.lang.annotation.*;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyExcludeComponent {
}

애너테이션 두개를 생성한다. 

 

package hello.core.scan.filter;

@MyIncludeComponent
public class BeanA {
}
package hello.core.scan.filter;

@MyExcludeComponent
public class BeanB {
}

BeanA ,BeanB 클래스를 생성하고 

BeanA 에는 MyIncludeComponent

BeanB 에는 MyExcludeComponent 애너테이션을 추가한다.

 

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.*;
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);
        Assertions.assertThat(beanA).isNotNull();

        org.junit.jupiter.api.Assertions.assertThrows(
                NoSuchBeanDefinitionException.class,
                () -> ac.getBean("beanB",BeanB.class));
    }


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

    }
}

ComponentFilterAppConfig 설정정보 클래스에 

@ComponentScan의 필터기능을 사용하여

includeFilters에 MyIncludeComponent 애너테이션을 추가하여 BeanA가 스프링 빈에 등록되고

excludeFilters에 MyExcludeComponent 애너테이션을 추가하여 BeanB는 스프링 빈에 등록되지 않는다.

 

FilterType 옵션

 

5가지 옵션이 있다.

 

ANNOTATION :  기본값, 애너테이션을 인식하여 동작

ASSIGNABLE_TYPE : 지정한 타입과 자식 타입을 인식하여 동작한다.

ASPECTJ : AspectJ패턴 사용

REGEX : 정규 표현식

CUSTOM : TypeFilter 라는 인터페이스를 구현해서 처리

+ Recent posts