[Lecture - 김영한님(스프링 핵심 원리 - 기본편)] 컴포넌트 스캔과 의존관계 자동 주입 시작하기
inflearn에서 김영한님 강의를 들으면서 내용을 정리해보자. 
 스프링 핵심 원리 - 기본편
컴포넌트 스캔과 의존관계 자동 주입 시작하기
스프링은 설정 정보가 없어도 자동으로 스프링 빈을 등록하는 컴포넌트 스캔이라는 기능을 제공한다. 
 또 의존관계도 자동으로 주입하는 @Autowired라는 기능도 제공한다.
1
2
3
4
5
6
7
@Configuration
@ComponentScan(
        excludeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Configuration.class)
)
public class AutoAppConfig {
}
- 컨포넌트 스캔을 사용하려면 먼저 @ComponentScan을 설정 정보에 붙여주면 된다.
- 기존의 AppConfig와는 다른게 @Bean으로 등록한 클래스가 하나도 없다.컴포넌트 스캔을 사용하려면 @Configuration이 붙은 설정 정보도 자동으로 등록되기 때문에 AppConfig, TestConfig 등 앞서 만들어두었던 설정 정보도 함께 등록되고 실행된다.
 그래서excludeFilters를 이용해서 설정 정보는 컴포넌트 스캔 대상에서 제외했다.
 보통 설정 정보를 컨포넌트 스캔 대상에서 제외하지는 않지만 기존 예제 코드를 최대한 남기고 유지하기 위해 이 방법을 사용했다.
컴포넌트 스캔은 이름 그대로 Component 애너테이션이 붙은 클래스를 스캔해서 스프링 빈으로 등록한다.
Configuration이 컴포넌트 스캔의 대상이 된 이유도@Configuration소스코드를 열어보면@Component애너테이션이 붙어있기 때문이다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// MemoryMemberRepository.java
@Component
public class MemoryMemberRepository implements MemberRepository {
    ...
}
// RateDiscountPolicy.java
@Component
public class RateDiscountPolicy implements DiscountPolicy {
    ...
}
// MemberSerivceImpl.java
@Component
public class MemberServiceImpl implements MemberService {
    private final MemberRepository memberRepository;
    @Autowired
    public MemberServiceImpl(MemberRepository memberRepository) {
      this.memberRepository = memberRepository;
    }
    ...
}
// OrderServiceImpl.java
@Component
public class OrderServiceImpl implements OrderService {
    private final MemberRepository memberRepository;
    private final DiscountPolicy discountPolicy;
    @Autowired
    public OrderServiceImpl(MemberRepository memberRepository, DiscountPolicy discountPolicy) {
      this.memberRepository = memberRepository;
      this.discountPolicy = discountPolicy;
    }
    ...
}
기존 코드에 @Component와 @Autowired를 추가한다.
@Autowired를 사용하면 생성자에서 여러 의존관계도 한번에 주입받을 수 있다.
1
2
3
4
5
6
7
8
9
public class AutoAppConfigTest {
    @Test
    void  basicScan() {
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AutoAppConfig.class);
        MemberService memberService = ac.getBean(MemberService.class);
        Assertions.assertThat(memberService).isInstanceOf(MemberService.class);
    }
}
- AnnotationConfigApplicationContest를 사용하는 것은 기존과 동일하다.
- 설정 정보로 AutoAppConfig 클래스를 넘겨준다.
- 실행해보면 기존과 같이 잘 동작한다.
컴포넌트 스캔과 자동 의존관계 주입 동작
- @ComponentScan
 - @ComponentScan은- @Component가 붙은 모든 클래스를 스프링 빈으로 등록한다.
- 이때 스프링 빈의 기본 이름은 클래스명을 사용하되 맨 앞글자만 소문자를 사용한다.- 빈 이름 기본 전략: MemberServiceImpl 클래스 -> memberServiceImpl
- 빈 이름 직접 지정: 만약 스프링 빈의 이름을 직접 지정하고 싶으면 @Component("memberService2")처럼 이름을 부여하면 된다.
 
 
- @Autowired의존관계 자동 주입
 - 생성자에 @Autowired를 지정하면, 스프링 컨테이너가 자동으로 해당 스프링 빈을 찾아서 주입한다.
- 이때 기본 조회 전략은 타입이 같은 빈을 찾아서 주입한다.- getBean(MemberRepository.class)와 동일하다고 이해하면 된다. (더 자세한 내용은 뒤에서 설명)
 
 - 생성자에 파라미터가 많아도 다 찾아서 자동으로 주입한다.
 
- 생성자에 
 This post is licensed under  CC BY 4.0  by the author.