Back-end

06. 컴포넌트 스캔

-운- 2023. 10. 31. 15:38

컴포넌트 스캔과 의존관계 자동 주입 시작하기

 

지금까지 우리가 빈을 등록할 때는 @Bean을 계속 써내려갔다.

만약 할게 많으면 수백개를 해야될 수도 있다.

스프링에서는 자동으로 스프링 빈을 등록하는 컴포넌트 스캔이라는 기능을 제공한다.

의존관계도 자동으로 주입하는 @Autowired라는 기능 또한 제공한다.

 

AutoAppConfig를 새로 만들자.

package hello.core;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import static org.springframework.context.annotation.ComponentScan.*;
@Configuration
@ComponentScan(
        excludeFilters = @Filter(type = FilterType.ANNOTATION, classes =
                Configuration.class))
public class AutoAppConfig {

}

 

컴포넌트 스캔을 사용하기위해 @ComponentScan을 설정 정보에 붙여주면 된다.

/* 컴포넌트 스캔을 사용하면 @Configuration 이 붙은 설정 정보도 자동으로 등록되기 때문에, AppConfig, TestConfig 등 앞서 만들어두었던 설정 정보도 함께 등록되고, 실행되어 버리므로  excludeFilters 를 이용해 설정정보는 컴포넌트 스캔 대상에서 제외.

보통 설정 정보를 컴포넌트 스캔 대상에서 제외하지는 않지만, 기존 예제 코드를 최대한 남기고 유지하기 위해서 이 방법을 선택하였다고 한다.*/

이제 각 클래스에 @Component를 붙여주자.

@Component
public class MemberServiceImpl implements MemberService {
    private final MemberRepository memberRepository;
    @Autowired
    public MemberServiceImpl(MemberRepository memberRepository) {
        this.memberRepository = memberRepository;
    }
}

 

이렇게 각 클래스 위에 @Component를 붙여주면 되고,

@Autowired는 의존 관계를 자동으로 주입해주는 것이며, 생성자에서 여러 의존관계도 한번에 주입받을 수 있다.

 

test

package hello.core.scan;
import hello.core.AutoAppConfig;
import hello.core.member.MemberService;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import
        org.springframework.context.annotation.AnnotationConfigApplicationContext;
import static org.assertj.core.api.Assertions.*;
public class AutoAppConfigTest {
    @Test
    void basicScan() {
        ApplicationContext ac = new AnnotationConfigApplicationContext(AutoAppConfig.class);
        MemberService memberService = ac.getBean(MemberService.class);
        assertThat(memberService).isInstanceOf(MemberService.class);
    }
}

Test를 보면 설정 정보를 입력하지 않아도 잘 동작하는 것을 알 수 있다.

기존의 ApplicationContext ac = new AnnotationConfigApplicationContext(AutoAppConfig.class); 는 사용하는 것이 동일하다.

 

탐색 위치와 기본 스캔 대상

탐색할 패키지의 시작 위치 지정

모든 자바 클래스를 다 컴포넌트 스캔하면 시간이 오래걸리므로 시작 위치를 지정할 수 있다.

@ComponentScan(
	basePackages = "hello.core",
}
  • basePackages : 탐색할 패키지의 시작 위치를 지정한다. 이 패키지를 포함해서 하위 패키지를 모두 탐색한다.
  • basePackages = {"hello.core", "hello.service"} 이렇게 여러 시작 위치를 지정할 수도 있다.
  • basePackageClasses : 지정한 클래스의 패키지를 탐색 시작 위치로 지정한다.

만약 지정하지 않으면 @ComponentScan 이 붙은 설정 정보 클래스의 패키지가 시작 위치가 된다

 

권장하는 방법

패키지 위치를 지정하는 것보다 설정 정보 클래스의 위치를 프로젝트 최상단에 두는 것.

예를 들어서 프로젝트가 다음과 같이 구조가 되어 있으면

  • com.hello
  • com.hello.serivce
  • com.hello.repository

 

com.hello 프로젝트 시작 루트, 여기에 AppConfig 같은 메인 설정 정보를 두고, @ComponentScan 애노테이션을 붙이고, basePackages 지정은 생략한다

이렇게 하면 com.hello 를 포함한 하위는 모두 자동으로 컴포넌트 스캔의 대상이 된다

참고로 스프링 부트를 사용하면 스프링 부트의 대표 시작 정보인 @SpringBootApplication 를 이 프로젝트 시작 루트 위치에 두는 것이 관례

 

컴포넌트 스캔 기본 대상

컴포넌트 스캔은 @Component 뿐만 아니라 다음과 내용도 추가로 대상에 포함한다.

  • @Component : 컴포넌트 스캔에서 사용
  • @Controller : 스프링 MVC 컨트롤러에서 사용, 스프링 MVC 컨트롤러로 인식
  • @Service : 스프링 비즈니스 로직에서 사용, 개발자들이 핵심 비즈니스 로직이 여기에 있 겠구나 라고 비즈니스 계층을 인식하는데 도움
  • @Repository : 스프링 데이터 접근 계층에서 사용, 스프링 데이터 접근 계층으로 인식하고, 데이터 계층의 예외를 스프링 예외로 변환
  • @Configuration : 스프링 설정 정보에서 사용, 이 스프링 설정 정보로 인식하고, 스프링 빈이 싱글톤을 유지하도록 추가 처리

 

필터

includeFilters : 컴포넌트 스캔 대상을 추가로 지정한다.

excludeFilters : 컴포넌트 스캔에서 제외할 대상을 지정한다.

 

예제

추가할 애노테이션

package hello.core.scan.filter;
import java.lang.annotation.*;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyIncludeComponent {
}

제외할 애노테이션

package hello.core.scan.filter;
import java.lang.annotation.*;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyExcludeComponent {
}

추가할 클래스

package hello.core.scan.filter;
@MyIncludeComponent
public class BeanA {
}

제외할 클래스

package hello.core.scan.filter;
@MyExcludeComponent
public class BeanB {
}

추가할 클래스와 제외할 클래스에는 각 추가할, 제외할 애노테이션을 적용해주었다.

 

test

package hello.core.scan.filter;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import
        org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.context.annotation.ComponentScan.Filter;
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 = FilterType.ANNOTATION, classes =
                    MyExcludeComponent.class)
    )
    static class ComponentFilterAppConfig {
    }
}

includeFilters 에 MyIncludeComponent 애노테이션을 추가해서 BeanA가 스프링 빈에 등록된다.

excludeFilters 에 MyExcludeComponent 애노테이션을 추가해서 BeanB는 스프링 빈에 등록되지 않는다.

 

FilterType 옵션 

1. ANNOTATION: 기본값, 애노테이션을 인식해서 동작한다.

ex) org.example.SomeAnnotation

2. ASSIGNABLE_TYPE: 지정한 타입과 자식 타입을 인식해서 동작한다.

ex) org.example.SomeClass

3. ASPECTJ: AspectJ 패턴 사용

ex) org.example..*Service+

4. REGEX: 정규 표현식

ex) org\.example\.Default.*

5. CUSTOM: TypeFilter 이라는 인터페이스를 구현해서 처리 ex

) org.example.MyTypeFilter

 

ex) BeanA를 빼고 싶으면 이걸 추가하면 됨.

@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)
        }
)

 

자동 빈 등록 vs 수동 빈 등록

컴포넌트 스캔에 의해 자동으로 스프링 빈이 등록되는데, 이름이 같으면 

ConflictingBeanDefinitionException 예외를 발생시킨다.

@Component
public class MemoryMemberRepository implements MemberRepository {}
@Configuration
@ComponentScan(
        excludeFilters = @Filter(type = FilterType.ANNOTATION, classes =
                Configuration.class)
)
public class AutoAppConfig {
    @Bean(name = "memoryMemberRepository")
    public MemberRepository memberRepository() {
        return new MemoryMemberRepository();
    }
}

이러한 겨우에는 수동 빈이 우선권을 가짐( 수동 빈이 자동 빈을 오버라이딩)