1. @ComponentScan
- @Bean붙일 필요 없이 @Component적힌 자동 스프링 빈 등록 (하나의 AppConfig로 관리 안해도 됨.)
- @ComponentScan시 @Configuration 붙은 설정들도 자동 등록 됨
- basePackages를 이용해 시작 위치를 지정할 수 있다.
- 이때 이 패키지를 포함해서 하위 패키지를 모두 탐색
- basePackage = { "hello.core", "hello.service"} 이렇게 여러 시작 위치 지정할 수도 있다.
- 지정하지 않으면 @ComponentScan이 붙은 설정 정보 클래스의 패키지가 시작 위치가 된다.
- 권장방법1: 설정 정보클래스의 위치를 프로젝트 최상단에 두기
- 권장방법2: 스프링 부트면 @SpringBootApplication를 프로젝트 시작 루트 위치에 두기.
2. @Component
- @Component붙이면 컴포넌트 스캔시 스프링빈 등록
- 의존성 주입이 AppConfig에 의해 이루어 지지 않아서 @Autowired등의 도움을 받음.
- 이때 스프링 빈의 기본 이름은 클래스명 사용하되 앞글자만 소문자
- @Component("memberService2")이렇게 이름 부여도 가능.
- 다음의 내용도 스캔 대상에 포함
- @Controller, @Service, @Repository(데이터 계층 예외 스프링 예외로 변환.) , @Configuration
3.@Filter
- 이렇게 등록후 아래에서 @Filter로 커스터마이징 가능.
@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 {
}
}
- 옵션
- ANNOTATION: 기본값, 애노테이션을 인식해서 동작.
- ASSIGNABLE_TYPE: 지정한 타입과 자식 타입을 인식해서 동작.
- ASPECTJ: AspectJ패턴 사용
- REGEX: 정규 표현식
- CUSTOM: TypeFilter라는 인터페이스 구현해서 처리
- ** 스프링 부트는 컴포넌트 스캔을 기본으로 제공. 옵션을 변경하기 보다 스프링 기본값 최대한 맞추어 사용 권장.
5. 등록과 충돌
- 자동빈끼리 이름 같은 경우: ConflictingBeanDefinitionException예외 발생.
- 수동, 자동충돌시 : 수동 빈등록이 우선. (스프링부트에서는 충돌 오류 나도록 기본값 변경됨.)
-
spring.main.allow-bean-definition-overriding=true 등록(Application.properties로 변경 가능)
-
'Spring > 기본' 카테고리의 다른 글
싱글톤 (웹과 관련하여) (1) | 2024.01.17 |
---|---|
의존성 (1) | 2024.01.16 |