@Bean이나 XML의 <bean>을 통해 설정 정보에 직접 등록할 스프링 빈을 나열했다.@Autowired기능도 제공한다.@Configuration
@ComponentScan(
excludeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Configuration.class)
// 자동으로 등록되는 컴포넌트 스캔 중에 뺄 거를 지정해준다
)
public class AutoAppConfig {
}
컴포넌트 스캔을 사용하려면 먼저 @ComponentScan을 설정 정보에 붙여주면 된다.
기존의 AppConfig와는 다르게 @Bean으로 등록한 클래스가 하나도 없다.
참고
- 컴포넌트 스캔을 사용하면
@Configuration이 붙은 설정 정보도 자동으로 등록되기 때문에, AppConfig, TestConfig 등 앞서 만들어두었던 설정 정보도 함께 등록되고, 실행되어 버린다.excludefilters를 이용해서 설정정보는 컴포넌트 스캔 대상에서 제외했다.- 보통 설정 정보를 컴포넌트 스캔 대상에서 제외하지는 않지만, 기존 예제 코드를 최대한 유지하기 위해 이 방법을 선택했다.
💡 여기서 궁금증 발생..!
AutoAppConfig에도@Configuration이 붙는데, 그렇다면 제외 항목에 해당되는 것이 아닐까? 라는 궁금증이 발생했다.
@ComponentScan에서 제외 처리된AppConfig,TestConfig는 내부 수동 빈 등록과 관련된 정보가 있다.@ComponentScan제외 처리할 땐excludeFilters의 조건에 따라 제외처리 하며 이때 자신은 해당되지 않는다.
컴포넌트 스캔은 이름 그대로 @Component 에노테이션이 붙은 클래스를 스캔해서 스프링 빈으로 등록한다.
@Configuration이 컴포넌트 스캔의 대상이 된 이유도 @Configuration 소스코드를 열어보면 @Component 애노테이션이 붙어있기 때문이다.
먼저, 아래와 같이 우리가 사용하는 클래스(MemberServiceImp, MemoryMemberRepository, OrderServiceImp, RateDiscountPolicy)에 @Component를 붙여주자!
/* 각 클래스에 @Component 추가```
@Component
public class MemberServiceImp implements MemberService{
private final MemberRepository memberRepository;
...
}
@Bean으로 직접 설정 정보를 작성했고, 의존관계도 직접 명시했다.@Autowired를 통해 의존관계를 자동 주입함으로써 해결한다.@Autowired를 사용하면 생성자에서 여러 의존관계도 한번에 주입받을 수 있다.
@Component
public class MemberServiceImp implements MemberService{
private final MemberRepository memberRepository;
@Autowired
public MemberServiceImp(MemberRepository memberRepository) {
this.memberRepository = memberRepository;
}
...
}
public class AutoAppConfigTest {
@Test
void basicScan(){
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AutoAppConfig.class);
MemberService memberService = ac.getBean(MemberService.class);
assertThat(memberService).isInstanceOf(MemberService.class);
}
}
AnnotationConfigApplicationContext를 사용하는 것은 기존과 동일하다.AutoAppConfig 클래스를 넘겨준다.로그를 살펴보면 컴포넌트 스캔이 식별 후보가 아래와 같이 등록되면서 잘 동작하는 것을 확인할 수 있다.
ClassPathBeanDefinitionScanner -
Identified candidate component class: file [C:\study2\core\out\production\classes\hello\core\discount\RateDiscountPolicy.class]
Identified candidate component class: file [C:\study2\core\out\production\classes\hello\core\member\MemberServiceImp.class]
Identified candidate component class: file [C:\study2\core\out\production\classes\hello\core\member\MemoryMemberRepository.class]
Identified candidate component class: file [C:\study2\core\out\production\classes\hello\core\order\OrderServiceImp.class]
또한 아래와 같이 @Autowired에 의해 의존관계가 자동 주입된것을 확인할 수 있다.
Autowiring by type from bean name 'memberServiceImp' via constructor to bean named 'memoryMemberRepository'
09:55:22.949 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory

@ComponentScan은 @Component가 붙은 모든 클래스를 스프링 빈으로 등록한다.빈 이름 기본 전략 :
MemberServiceImpl클래스 →memberServiceImpl
빈 이름 직접 지정 : 스프링 빈 이름을 직접 지정하고 싶으면@Component("memberService2")이런식으로 이름을 부여한다.

@Autowired를 지정하면, 스프링 컨테이너가 자동으로 해당 스프링 빈을 찾아서 주입한다.이때 기본 조회 전략은 타입이 같은 빈을 찾아서 주입한다.
getBean(MemberRepository.class)와 동일하다고 이해하면 된다.

탐색할 패키지의 시작 위치 지정
모든 자바 클래스를 다 컴포넌트 스캔하면 시간이 오래 걸린다.
그래서 꼭 필요한 위치부터 탐색하도록 시작 위치를 지정할 수 있다.
@Configuration
@ComponentScan(
basePackages = "hello.core.member",
// 탐색할 패키지의 시작 위치를 지정한다
excludeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Configuration.class)
// 자동으로 등록되는 컴포넌트 스캔 중에 뺄 거를 지정해준다
)
public class AutoAppConfig {
}
basePackages : 탐색할 패키지의 시작 위치를 지정한다. 이 패키지를 포함해서 하위 패키지 모두 탐색한다.basePackages = {"hello.core", "hello.service"} 과 같이 여러 시작 위치를 지정할 수 있다.basePackageClassess : 지정한 클래스의 패키지를 탐색 시작 위치로 지정한다.@ComponentScan이 붙은 설정 정보 클래스의 패키지가 시작 위치가 된다.권장하는 방법
개인적으로 즐겨 사용하는 방법은 설정 정보 클래스의 위치를 프로젝트 최상단에 두는 것이다.
프로젝트가 다음과 같이 구조가 되어 있으면...🔎
com.hello
com.hello.service
com.hello.repository
com.hello→ 프로젝트 시작 루트, 여기에 AppConfig 같은 메인 설정 정보를 두고,@ComponentScan애노테이션을 붙이고,basePackages지정은 생략한다.
com.hello를 포함한 하위는 모두 자동으로 컴포넌트 스캔의 대상
프로젝트 메인 설정 정보는 프르젝트를 대표하는 정보이기 때문에 시작 루트에 위치에 두는 것이 좋다!
스프링 부트를 사용하면 스프링 부트 대표 시작 정보인@SpringBootApplication를 프로젝트 시작 루트 위치에 두는 것이 관례!
( 이 설정 안에@ComponentScan이 들어있다 )
컴포넌트 스캔은 @Component뿐만 아니라 다음 내용도 추가로 대상에 포함된다.
@Component : 컴포넌트 스캔에서 사용@Controller : 스프링 MVC 컨트롤러에서 사용@Service : 스프링 비즈니스 로직에서 사용@Repository : 스프링 데이터 접근 계층에서 사용@Configuration : 스프링 설정 정보에서 사용해당 클래스의 소스 코드를 보면 @Component를 포함하고 있는 것을 알 수 있다.

애노테이션은 상속이라는 개념이 없다! 애노테이션은 스프링이 지원하는 기능!
컴포넌트 스캔의 용도 뿐만 아니라 다음 애노테이션이 있으면 스프링은 부가 기능을 수행한다.
@Controller : 스프링 MVC 컨트롤러로 인식@Repository : 스프링 데이터 접근 계층으로 인식하고, 데이터 계층의 예외를 스프링 예외로 변환해준다.@Configuration : 스프링 설정 정보로 인식하고, 스프링 빈이 싱글톤을 유지하도록 추가 처리를 한다.@Service : 특별한 처리는 없지만 개발자들이 핵심 비즈니스 로직이 여기에 있다는 것을 인식할 수 있는데 도움이 된다.
userDefaultFilters옵션은 기본으로 켜져 있는데 이 옵션을 끄면 기본 스캔 대상에서 제외됨!
컴포넌트 스캔의 추가 혹은 제외 대상을 각각 지정할 수 있다.
includeFilters : 컴포넌트 스캔 대상을 추가로 지정excludeFilters : 컴포넌트 스캔에서 제외할 대상 지정@Target(ElementType.TYPE) // 어디에 붙는지? TYPE은 class 레벨에 붙는 것!
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyExcludeComponent {
}
@Target(ElementType.TYPE) // 어디에 붙는지? TYPE은 class 레벨에 붙는 것!
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyIncludeComponent {
}
@MyIncludeComponent 적용
package hello.core.scan.filter;
@MyIncludeComponent
public class BeanA {
}
@@MyExcludeComponent 적용
@MyExcludeComponent
public class BeanB {
}
public class ComponentFilterAppConfigTest {
@Test
void filterScan(){
ApplicationContext ac = new AnnotationConfigApplicationContext(ComponentFilterAppConfig.class);
BeanA beanA = ac.getBean("beanA", BeanA.class);
assertThat(beanA).isNotNull();
BeanB beanB = 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 {
}
}
Container에 BeanB은 빈으로 등록되어 있지 않으므로 Exception 에러가 뜨게 된다.

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)
);
}
includeFilters 에 @MyIncludeComponent를 추가해서 BeanA가 스프링 빈에 등록된다.excludeFilters에 @MyExcludeComponent를 추가해서 BeanB가 스프링 빈에 등록되지 않는다.
- ANNOTATION : 기본값, 애노테이션을 인식해서 동작
- ASSIGNABLE_TYPE : 지정한 타입과 자식 타입을 인식해서 동작
- ASPECTJ : Aspect.J 패턴 사용
- REGEX : 정규 표현식
- CUSTOM : TypeFilter이라는 인터페이스를 구현해서 처리
다음과 같이 ASSIGNABLE_TYPE(지정한 타입과 자식 타입을 인식해서 동작)을 이용해서 BeanA도 추가적으로 뺄 수 있다.
@Configuration
@ComponentScan(
includeFilters = @Filter(type = FilterType.ANNOTATION, classes = MyIncludeComponent.class),
excludeFilters = {
@Filter(type = FilterType.ANNOTATION, classes = MyExcludeComponent.class),
@Filter(type = FilterType.ASSIGNABLE_TYPE, classes = BeanA.class)
}
)
static class ComponentFilterAppConfig {
}
@Component면 충분하기 때문에includeFilters를 사용할 일이 많지 않다.excludeFilters또한 마찬가지!
스프링 부트는 컴포넌트 스캔을 기본으로 제공하는데, 옵션을 변경하면서 사용하기 보다는 스프링의 기본 설정에 최대한 맞추어 사용하는 것을 권장한다.
컴포넌트 스캔에서 같은 빈 이름을 등록하면 어떻게 될까?
ConflictingBeanDefinitionException 발생org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [hello.core.AutoAppConfig]; nested exception is org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'service' for bean class [hello.core.order.OrderServiceImp] conflicts with existing, non-compatible bean definition of same name and class [hello.core.member.MemberServiceImp]만약 수동 빈 등록과 자동 빈 등록에서 빈 이름이 충돌되면 어떻게 될까?
@Configuration
@ComponentScan(
excludeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Configuration.class)
// 자동으로 등록되는 컴포넌트 스캔 중에 뺄 거를 지정해준다
)
public class AutoAppConfig {
// 수동 빈 등록
// 이미 자동 빈 등록으로 memoryMemberRepository가 등록되어 있는 상태!
@Bean(name = "memoryMemberRepository")
MemberRepository memberRepository(){
return new MemoryMemberRepository();
}
}
이 경우 수동 빈 등록이 우선권을 가진다.
( 수동 빈이 자동 빈을 오버라이딩 해버린다 )
Overriding bean definition for bean 'memoryMemberRepository' with a different definition: replacing
스프링 부트인 coreApplication을 실행해보면 오류를 볼 수 있다.
Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true