출처. inflearn, 김영한 스프링 핵심 원리 - 기본편
@Autowired
라는 기능도 제공한다.코드로 컴포넌트 스캔과 의존과계 자동 주입을 알아보자.
먼저 기존 AppConfig.java는 과거 코드와 테스트를 유지하기 위해 남겨두고, 새로운 AutoAppConfig.java를 만들자.
AutoAppConfig.java
@Configuration
@ComponentScan(excludeFilters = @Filter(type = FilterType.ANNOTATION, classes = Configuration.class))
public class AutoAppConfig{
}
@ComponentScan
을 설정 정보에 붙여주면 된다.참고: 컴포넌트 스캔을 사용하면
@Configuration
이 붙은 설정 정보도 자동으로 등록되기 때문에, AppConfig, TestConfig 등 앞서 만들어두었던 설정 정보도 함께 등록되고, 실행되어 버린다. 그래서excludeFilters
을 이용해서 설정정보는 컴포넌트 스캔 대상에서 제외했다. 보통 설정 정보를 컴포넌트 스캔 대상에서 제외하지는 않지만, 기존 예제 코드를 최대한 남기고 유지하기 위해서 이 방법을 선택했다.
컴포넌트 스캔은 이름 그대로 @Component
애노테이션이 붙은 클래스를 스캔해서 스프링 빈으로 등록한다. @Component
를 붙어주자.
참고:
@Configuration
이 컴포넌트 스캔의 대상이 된 이유도@Configuration
소스코드를 열어보면@Component
애노테이션이 붙어있기 때문이다.
이제 각 클래스가 컴포넌트 스캔의 대상이 되도록 @Component
애노테이션을 붙어주자.
MemoryMemberRepository @Component 추가
@Component
public class MemoryMemberRepository implements MemberRepository{}
RateDiscountPolicy @Component 추가
@Component
public class RateDiscountPolicy implements DiscountPolicy {}
MemberServiceImpl @Component, @Autowired 추가
@Component
public class MemberServiceImpl implements MemberService {
private final MemberRepository MemberRepository;
@Autowired
public MemberServiceImpl(MemberRepository memberRepository){
this.memberRepository = memberRepository;
}
}
@Bean
으로 직접 설정 정보를 작성했고, 의존관계도 직접 명시했다. 이제는 이런 설정 정보 자체가 없기 때문에, 의존관계 주입도 이 클래스 안에서 해결해야 한다.@Autowired
는 의존 관계를 자동으로 주입해준다. 자세한 룰은 조금 뒤에 설명하겠다.OrderServiceImpl @Component, @Autowired 추가
@Component
public class OrderServiceImpl implements OrderSercice{
private final MemberRepository memberRepositoy;
private final DiscountPolicy discountPolicy;
@Autowired
public OrderServiceImpl(MemberRepository memberRepository, DiscountPolicy discountPolicy){
this.memberRepository = memberRepositoty;
this.discountPolicy = discountPolicy;
}
}
AutoAppConfigTest.java
public class AutoAppConfigTest{
@Test
void basicScan(){
ApplicationContext ac = new AnnotationConfigAppilcationContext(AutoAppConfig.class);
MemberService memberService = ac.getBean(MemberService.class);
assertThat(memberService).isInstanceOf(MemberService.class);
}
}
AnntationConfigApplicationContext
를 사용하는 것은 기존과 동일한다.AutoAppConfig
클래스를 넘겨준다.로그를 잘 보면 컴포넌트 스캔이 잘 동작하는 것을 확인할 수 있다.
ClassPathBeanDefinitionScanner - identified canditate component class:
・・ RateDiscountPolicy.class
・・ MemberServiceImpl.class
・・ MemoryMemberRepository.class
・・ OrderServiceImpl.class
컴포넌트 스캔과 자동 의존관계 주입이 어떻게 동작하는지 그림으로 알아보자.
1.ComponentScan
@ComponentScan
은 @Component
가 붙은 모든 클래스를 스프링 빈으로 등록한다.@Component("memberService2")
이런식으로 이름을 부여하면 된다.2. @Autowired 의존관계 자동 주입
@Autowired
를 지정하면, 스프링 컨테이너가 자동으로 해당 스프링 빈을 찾아서 주입한다.getBean(MemberRepository.class)
와 동일하다고 이해하면 된다.탐색할 패키지의 시작 위치 지정
모든 자바 클래스를 다 컴포넌트 스캔하면 시간이 오래 걸린다. 그래서 꼭 필요한 위치부터 탐색하도록 시작 위치를 지정할 수 있다.
@ComponentScan{
basePackages = "hello.core",
}
basePackages
탐색할 패키지의 시작 위치를 지정한다. 이 패키지를 포함해서 하위 패키지를 모두 탐색한다.basePackagesg = {"hello.core", "hello.service"}
이렇게 여러 시작 위치를 지정할 수도 있다.basePackageClasses
: 지정한 클래스의 패키지를 탐색 시작 위치로 지정한다.@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
를 포함하고 있는 것을 알 수 있다.
@Component
public @interface Controller {
}
@Component
public @interface Service {
}
@Component
public @interface Configuration {
}
참고: 사실 애노테이션에는 상속관계라는 것이 없다. 그래서 이렇게 애노테이션이 특정 애노테이션을 들고 있는 것을 인식할 수 있는 것은 자바 언어가 지원하는 기능은 아니고, 스프링이 지원하는 기능이다.
컴포넌트 스캔의 용도 뿐만 아니라 다음 애노테이션이 있으면 스프링은 부가 기능을 수행한다.
@Controller
: 스프링 MVC 컨트롤러로 인식@Repository
: 스프링 데이터 접근 계층으로 인식하고, 데이터 계층의 예외를 스프링 예외로 변환해준다.@Configuration
: 앞서 보았듯이 스프링 설정 정보로 인식하고, 스프링 빈이 싱글톤을 유지하도록 추가 처리를 한다.@Service
: 사실 @Service
는 특별할 처리를 하지 않는다. 대신 개발자들이 핵심 비즈니스 로직이 여기에 있겠구나라고 비즈니스 계층을 인식하는데 도움이 된다.참고:
useDefaultFilters
옵션은 기본으로 켜져있는데, 이 옵션을 끄면 기본 스캔 대상들이 제외된다. 그냥 이런 옵션이 잏ㅆ구나 알고 넘어가자.
includeFilters
: 컴포넌트 스캔 대상을 추가로 지정한다.excludeFilters
: 컴포넌트 스캔에서 제외할 대상을 지정한다.빠르게 예제로 확인해보자.
모든 코드는 테스트 코드에 추가
컴포넌트 스캔 대상에 추가할 애노테이션
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyIncludeComponet{
}
컴포넌트 스캔 대상에서 제외할 애노테이션
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyExcludeComponent{
}
컴포넌트 스캔 대상에 추가할 클래스
@MyIncludeComponent
public class BeanA{
}
@MyIncludeComponent
적용설정 정보와 전체 테스트 코드
public class ComponentFilterAppConfigTest{
@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 = MyExcludeComponent.class)
)
static class ComponentFilterAppConfig{
}
}
@ComponentScan(
includeFilters = @Filter(type = FilterType.ANNOTATION, classes = MyIncludeComponent.class),
excludeFilters = @Filter(type = FilterType.ANNOTATION, classes = MyExcludeComponent.class)
)
includeFilters
에 MyIncludeComponent
애노테이션을 추가해서 BeanA가 스프링 빈에 등록된다.excludeFilters
에 MyExcludeComponent
애노테이션을 추가해서 BeanB 는 스프링 빈에 등록되지 않는다.FilterType 옵션
FilterType은 5가지 옵션이 있다.
org.example.SomeAnnotation
org.example.SomeClass
org.\example\.Default.*
TypeFilter
이라는 인터페이스를 구현해서 처리org.example.MyTypeFilter
예를 들어서 BeanA도 빼고 싶으면 다음과 같이 추가하면 된다.
@ComponentScan(
includeFilters = {
@Filter(type = FilterType.ANNOTATION, classes = MyIncludeComponent.class),
},
excludeFilters = {
@Filter(type = FilterType.ASSIGNABLE_TYPE, classes = BeanA.class)
}
}
참고:
@Component
면 충분하기 때문에,includeFilters
를 사용할 일은 거의 없다.excludeFilters
는 여러가지 이유로 간혹 사용할 때가 있지만 많지는 않다.
특히 최근 스프링 부트는 컴포넌트 스캔을 기본으로 제공하는데, 개인적으로는 옵션을 변경하면서 사용하기보다는 스프링의 기본 설정에 최대한 맞추어 사용하는 것을 권장하고, 선호하는 편이다.