지금까지는 빈 등록시 @bean 등을 통해 설정 정보에 직접 등록할 스프링 빈 나열 -> 비효율적
그래서! 스프링이 아래 두가지 기능 제공한다
@Component 애노테이션이 붙은 클래스를 스캔해서 스프링 빈으로 등록@Configuration
@ComponentScan // @Component 가 어노테이션이 붙은 클래스를 찾아서 전부 스프링 빈으로 등록해준다
(
excludeFilters = @ComponentScan.Filter(type= FilterType.ANNOTATION, classes = Configuration.class)
//Configuration 을 빼는 것(AppConfig 가 자동으로 등록되면 안되기 떄문)
)
public class AutoAppConfig {
}
@Autowired 를 지정하면, 스프링 컨테이너가 자동으로 해당 스프링 빈을 찾아서 주입
// 대상에 추가할 애노테이션
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyIncludeComponent {
}
// 대상에 제외할 애노테이션
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyExcludeComponent {
}
@Test
void filterScan(){
ApplicationContext ac = new AnnotationConfigApplicationContext(ComponentFilterAppConfig.class);
BeanA beanA = ac.getBean("beanA", BeanA.class);
assertThat(beanA).isNotNull();
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 {
}
TypeFilter 이라는 인터페이스를 구현해서 처리최근에 스프링 부트는 오류 발생하도록 바뀜
