[Java/Spring] Component Scan

이나영·2022년 6월 23일
0

Spring Boot

목록 보기
3/3

@ComponentScan

spring 프로젝트 개발 시 스프링 빈과 의존관계를 주입하기 위해 @Bean 이나 XML의 <Bean> 등 설정 정보에 직접 코드를 작성해야한다.

ex.

package hello.core;

import hello.core.discount.DiscountPolicy;
import hello.core.discount.FixDiscountPolicy;
import hello.core.discount.RateDiscountPolicy;
import hello.core.member.MemberRepository;
import hello.core.member.MemberService;
import hello.core.member.MemberServiceImpl;
import hello.core.member.MemoryMemberRepository;
import hello.core.order.OrderService;
import hello.core.order.OrderServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {

    // 역할 (인터페이스) - 그 안에 구현 클래스 넣기

    @Bean
    public MemberService memberService() { // 생성자 주입
        return new MemberServiceImpl(memberRepository());
    }

    @Bean
    public OrderService orderService() {
        return new OrderServiceImpl(memberRepository(), discountPolicy());
    }

    //------------------------------
    // 구현 클래스

    @Bean
    public MemberRepository memberRepository() {
        return new MemoryMemberRepository(); // 추후 변경 시 여기만 고쳐주면 된다.
    }

    @Bean
    public DiscountPolicy discountPolicy() {
        return new RateDiscountPolicy();
    }
}

근데 @ComponentScan 을 설정 정보에 붙여주면 코드 작성 없이도 @Component 가 붙은 클래스를 모두 스캔하여 스프링 빈으로 자동 등록한다.

따라서 스프링 빈으로 등록하고 싶은 클래스에 @Component 어노테이션만 붙여준다면 따로 설정코드를 작성하지 않아도 된다.


package hello.core;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;

@Configuration
@ComponentScan(
        // 탐색할 시작 위치 지정 -> 모든 컴포넌트 스캔 시 시간이 오래걸리니까
        basePackages = "hello.core"
)
public class AutoAppConfig {
}

위의 코드처럼 AutoAppConfig 클래스 안에 아무것도 적혀 있지 않아도 자동 등록된다!


@Autowired

설정 정보 클래스 내부에서 의존관계도 주입해주었기 때문에, 설정 정보 코드가 없어졌으니 의존관계 주입도 자동으로 해주어야 한다.

@Component 가 붙은 클래스의 생성자에 @Autowired 를 지정하면 스프링 컨테이너가 자동으로 해당 스프링 빈을 찾아서 주입해준다.

  • getBean()과 동일한 기능을 한다.




👀 Inflearn -김영한 Spring 핵심원리 강의를 듣고 스스로 정리한 내용입니다. :)

profile
소통하는 백엔드 개발자로 성장하기

0개의 댓글