[SpringBasic] component-scan

shin·2022년 8월 16일
0

Spring Web Basic

목록 보기
5/5
post-thumbnail

1. 컴포넌트 스캔과 의존관계 자동 주입

1) 직접 스프링 빈을 등록하는 방식의 문제점

🚨 @Bean이나 XML의 <bean> 등을 통해서 설정 정보에 직접 등록할 스프링 빈을 나열하는 방식은 등록해야 하는 스프링 빈의 수가 많아지면 매번 등록하기 번거롭고 설정 정보도 커지고 누락되는 문제가 발생할 수 있음

😊 따라서 스프링은 설정 정보가 없어도 자동으로 스프링 빈을 등록하는 @ComponentScan 기능과 의존 관계를 자동으로 주입하는 @Autowired라는 기능을 제공함

2) @ComponentScan

package hello.core;

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

@Configuration
@ComponentScan(
        // 컴포넌트 스캔에서 제외할 것을 지정
        excludeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Configuration.class)
)
public class AutoAppConfig {
	// 기존의 AppConfig와 다르게 @Bean으로 등록한 클래스가 없음
}
  • 컴포넌트 스캔을 사용하기 위해서는 먼저 @ComponentScan을 설정 정보에 붙여주면 됨
  • 컴포넌트 스캔은 @Component annotation이 붙은 클래스를 스캔해서 스프링 빈으로 등록함
...
@Component
public @interface Configuration {
...
  • @Configuration이 붙은 설정 정보까지 자동으로 등록되지 않도록 하기 위해서 excludeFilters를 이용해서 설정 정보를 컴포넌트 스캔 대상에서 제외해줌
  • 실무에서는 설정 정보를 컴포넌트 스캔 대상에서 제외하지는 않지만, 기존 예제 코드를 최대한 남기기 위해 해당 방식을 사용함 (AppConfig, TestConfig 등 앞서 만들어뒀던 설정 정보 때문)

3) @Autowired

@Component
public class MemberServiceImpl implements MemberService {

    private final MemberRepository memberRepository;

  	// 자동 의존 관계 주입 - ac.getBean(MemberRepository.class)처럼 동작함
    @Autowired 
    public MemberServiceImpl(MemberRepository memberRepository) {
        this.memberRepository = memberRepository;
    }
  ...
}
  • MemoryMemberRepository, RateDiscountPolicy, MemberServiceImpl를 컴포넌트 스캔 대상에 추가하기 위해서 @Component를 추가함
  • 이전 AppConfig에서는 @Bean으로 직접 설정 정보를 작성하고 의존 관계도 직접 명시했지만, 이제는 이런 설정 정보 자체가 없기 때문에 의존 관계 주입도 이 클래스 내에서 해결해야 함
  • 따라서 @Autowired를 붙여서 의존 관계를 자동으로 주입해줌
@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;
    }
  ...
}
  • @Autowired를 사용하면 생성자에서 여러 의존 관계도 한 번에 주입받을 수 있음

4) Test

package hello.core.scan;
...
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 [... RateDiscountPolicy.class]
[... MemberServiceImpl.class]
[... MemoryMemberRepository.class]
[... OrderServiceImpl.class]
  • 로그를 확인해보면 컴포넌트 스캔이 잘 동작하는 것을 알 수 있음

5) 정리

  • @ComponentScan 정리
    • @Component가 붙은 모든 클래스를 스프링 빈으로 등록
    • 스프링 빈의 기본 이름은 클래스명을 사용하되 맨 앞글자만 소문자를 사용함
    • @Component("memberService2")와 같은 식으로 작성하면 스프링 빈의 이름을 직접 지정할 수 있음
  • @Autowired 정리
    • 생성자에 @Autowired를 지정하면 스프링 컨테이너가 자동으로 해당 스프링 빈을 찾아서 주입함
    • 이때 기본 조회 전략은 타입이 같은 빈을 찾아서 주입
    • getBean(MemberRepository.class)와 동일
    • 생성자에 파라미터가 많아도 다 찾아서 자동으로 주입함

2. 탐색 위치와 기본 스캔 대상

1) 탐색 위치 지정 (basePackages)

  • 꼭 필요한 위치부터 탐색하도록 시작 위치를 지정할 수 있음
...
@ComponentScan(
        basePackages = "hello.core.member", // 이 위치부터 컴포넌트 스캔을 시작함
        ...
)
...
  • basePackages : 탐색할 패키지의 시작 위치를 지정함

    • 해당 패키지를 포함해서 하위 패키지를 모두 탐색
    • basePackages = {"hello.core", "hello.service"}와 같은 형태로 여러 시작 위치를 지정할 수도 있음
    • 만약 탐색 위치를 지정하지 않으면 @ComponentScan이 붙은 설정 정보 클래스의 패키지가 시작 위치가 됨
  • 따라서 위 코드의 경우 hello.core.member 패키지 아래에 있는 MemoryMemberRepositoryMemberServiceImpl 클래스만 컴포넌트 스캔의 대상이 됨

2) 권장하는 방법

  • 패키지 위치를 지정하지 않고 설정 정보 클래스의 위치를 프로젝트 최상단에 두는 방법을 권장함

  • 스프링 부트도 이 방법을 기본으로 제공함

  • 프로젝트 메인 설정 정보는 프로젝트를 대표하는 정보이기 때문에 프로젝트 시작 루트 위치에 두는 것이 좋음

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

package hello.core; // 프로젝트 시작 루트
...
@SpringBootApplication
public class CoreApplication {
...
}
...
@ComponentScan(...) // 설정 안에 바로 들어가 있음
public @interface SpringBootApplication {
...
}
  • 따라서 프로젝트 시작 루트AppConfig와 같은 메인 설정 정보를 두고, @ComponentScan annotation을 붙이고 basePackages를 생략하는 것이 좋음

3) 컴포넌트 스캔 기본 대상

  • 컴포넌트 스캔은 @Component뿐만 아니라 아래 내용도 대상에 포함함

    • @Component : 컴포넌트 스캔에서 사용

    • @Controller : 스프링 MVC 컨트롤러에서 사용

    • @Service : 스프링 비즈니스 로직에서 사용

    • @Repository : 스프링 데이터 접근 계층에서 사용

    • @Configuration : 스프링 설정 정보에서 사용

    • 해당 클래스들의 소스 코드를 보면 @Component를 포함하고 있음

  • 컴포넌트 스캔 외에 스프링 부가 기능

    • @Controller : 스프링 MVC 컨트롤러로 인식

    • @Repository : 스프링 데이터 접근 계층으로 인식하고, 데이터 계층의 예외를 스프링 예외로 변환해줌
      (기존 DB를 다른 DB로 변경하면 새로운 예외 발생으로 서비스와 같은 다른 코드를 모두 변경해야 하는 문제점을 해결해줌)

    • @Configuration : 스프링 설정 정보로 인식하고, 스프링 빈이 싱글톤을 유지하도록 추가 처리를 함

    • @Service : 특별한 처리를 하지는 않지만, 개발자들이 핵심 비즈니스 로직이 여기에 있겠구나라고 비즈니스 계층을 인식하는데 도움이 됨


3. 필터

1) includeFilters & excludeFilters

  • includeFilters : 컴포넌트 스캔 대상을 추가로 지정
  • excludeFilters : 컴포넌트 스캔에서 제외할 대상을 지정
package hello.core.scan.filter;

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
public @interface MyIncludeComponent {
}
package hello.core.scan.filter;

import java.lang.annotation.*;

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

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

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

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.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.springframework.context.annotation.ComponentScan.*;

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

    @Configuration
    @ComponentScan(
            includeFilters = @Filter(type = FilterType.ANNOTATION, classes = MyIncludeComponent.class),
            excludeFilters = @Filter(type = FilterType.ANNOTATION, classes = MyExcludeComponent.class)
    )
    static class ComponentFilterAppConfig {
    }

}
  • includeFiltersMyIncludeComponent annotation을 추가해서 BeanA가 스프링 빈에 등록됨
  • excludeFiltersMyExcludeComponent annotation을 추가해서 BeanB가 스프링 빈에 등록되지 않음

2) FilterType 옵션

  • ANNOTATION : 기본 값 (생략해도 됨)
    • ex) org.example.SomeAnnotation
  • ASSIGNABLE_TYPE : 지정한 타입과 자식 타입을 인식해서 동작함
    • ex) org.example.SomeClass
  • ASPECTJ : AspectJ 패턴 사용
    • ex) org.example..*Service+
  • REGEX : 정규 표현식
    • ex) org\.example\.Default.*
  • CUSTOM : TypeFilter라는 인터페이스를 구현해서 처리
    • ex) org.example.MyTypeFilter
@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)
            }
    )
  • BeanA를 스캔 대상에서 제외하고 싶다면 위 코드처럼 작성하면 됨
  • 하지만 @Component만으로 충분하고, 최근 스프링 부트는 컴포넌트 스캔을 기본으로 제공하기 때문에 옵션을 변경하면서 사용하기 보다는 스프링 기본 설정에 최대한 맞추어 사용하는 것을 권장함

4. 중복 등록과 충돌

1) 자동 빈 등록 vs 자동 빈 등록

  • ConflictingBeanDefinitionException 예외 발생
  • 이런 경우는 거의 없음

2) 수동 빈 등록 vs 자동 빈 등록

...
@Component
public class MemoryMemberRepository implements MemberRepository { ... }
...
public class AutoAppConfig {

	@Bean(name = "memoryMemberRepository")
    public MemberRepository memberRepository() {
    	return new MemoryMemberRepository();
    }
    
}
  • 이런 경우에는 수동 빈 등록이 우선권을 가짐 (수동 빈이 자동 빈을 오버라이딩)

  • 하지만 의도적으로 이런 결과를 만들었다기 보다는 여러 설정이 꼬여서 의도치 않게 이런 상황이 발생하는 경우가 많음

  • 그렇게 되면 '잡기 어려운 애매한 버그'가 만들어짐

  • 따라서 최근 스프링 부트는 수동 빈 등록과 자동 빈 등록의 충돌이 발생하면 오류가 발생하도록 기본 값을 변경함

Description:

The bean 'memoryMemberRepository', defined in class path resource [hello/core/AutoAppConfig.class], could not be registered. A bean with that name has already been defined in file [C:\Users\syb02\IdeaProjects\core\build\classes\java\main\hello\core\member\MemoryMemberRepository.class] and overriding is disabled.

Action:

Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true
  • CoreApplication을 실행해보면 위와 같은 오류가 발생함
spring.main.allow-bean-definition-overriding=true
  • 오류에서 설명한대로 application.properties에 코드를 붙여넣으면 오버라이딩이 설정되면서 오류가 발생하지 않고 실행됨
  • 하지만 확실하지 않은 애매한 상황은 발생하지 않도록 하는 것이 개발을 하는데 훨씬 도움이 됨

출처 : 스프링 핵심 원리 - 기본편

profile
Backend development

0개의 댓글

관련 채용 정보