🚨 @Bean
이나 XML의 <bean>
등을 통해서 설정 정보에 직접 등록할 스프링 빈을 나열하는 방식은 등록해야 하는 스프링 빈의 수가 많아지면 매번 등록하기 번거롭고 설정 정보도 커지고 누락되는 문제가 발생할 수 있음
😊 따라서 스프링은 설정 정보가 없어도 자동으로 스프링 빈을 등록하는 @ComponentScan
기능과 의존 관계를 자동으로 주입하는 @Autowired
라는 기능을 제공함
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
를 이용해서 설정 정보를 컴포넌트 스캔 대상에서 제외해줌@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
를 사용하면 생성자에서 여러 의존 관계도 한 번에 주입받을 수 있음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]
@Component
가 붙은 모든 클래스를 스프링 빈으로 등록- 스프링 빈의 기본 이름은 클래스명을 사용하되 맨 앞글자만 소문자를 사용함
@Component("memberService2")
와 같은 식으로 작성하면 스프링 빈의 이름을 직접 지정할 수 있음
- 생성자에
@Autowired
를 지정하면 스프링 컨테이너가 자동으로 해당 스프링 빈을 찾아서 주입함- 이때 기본 조회 전략은 타입이 같은 빈을 찾아서 주입
getBean(MemberRepository.class)
와 동일- 생성자에 파라미터가 많아도 다 찾아서 자동으로 주입함
...
@ComponentScan(
basePackages = "hello.core.member", // 이 위치부터 컴포넌트 스캔을 시작함
...
)
...
basePackages
: 탐색할 패키지의 시작 위치를 지정함
basePackages = {"hello.core", "hello.service"}
와 같은 형태로 여러 시작 위치를 지정할 수도 있음@ComponentScan
이 붙은 설정 정보 클래스의 패키지가 시작 위치가 됨따라서 위 코드의 경우 hello.core.member
패키지 아래에 있는 MemoryMemberRepository
와 MemberServiceImpl
클래스만 컴포넌트 스캔의 대상이 됨
패키지 위치를 지정하지 않고 설정 정보 클래스의 위치를 프로젝트 최상단에 두는 방법을 권장함
스프링 부트도 이 방법을 기본으로 제공함
프로젝트 메인 설정 정보는 프로젝트를 대표하는 정보이기 때문에 프로젝트 시작 루트 위치에 두는 것이 좋음
참고로 스프링 부트를 사용하면 스프링 부트의 대표 시작 정보인 @SpringBootApplication
을 시작 루트에 두는 것이 관례임
package hello.core; // 프로젝트 시작 루트
...
@SpringBootApplication
public class CoreApplication {
...
}
...
@ComponentScan(...) // 설정 안에 바로 들어가 있음
public @interface SpringBootApplication {
...
}
AppConfig
와 같은 메인 설정 정보를 두고, @ComponentScan
annotation을 붙이고 basePackages
를 생략하는 것이 좋음컴포넌트 스캔은 @Component
뿐만 아니라 아래 내용도 대상에 포함함
@Component
: 컴포넌트 스캔에서 사용
@Controller
: 스프링 MVC 컨트롤러에서 사용
@Service
: 스프링 비즈니스 로직에서 사용
@Repository
: 스프링 데이터 접근 계층에서 사용
@Configuration
: 스프링 설정 정보에서 사용
해당 클래스들의 소스 코드를 보면 @Component
를 포함하고 있음
컴포넌트 스캔 외에 스프링 부가 기능
@Controller
: 스프링 MVC 컨트롤러로 인식
@Repository
: 스프링 데이터 접근 계층으로 인식하고, 데이터 계층의 예외를 스프링 예외로 변환해줌
(기존 DB를 다른 DB로 변경하면 새로운 예외 발생으로 서비스와 같은 다른 코드를 모두 변경해야 하는 문제점을 해결해줌)
@Configuration
: 스프링 설정 정보로 인식하고, 스프링 빈이 싱글톤을 유지하도록 추가 처리를 함
@Service
: 특별한 처리를 하지는 않지만, 개발자들이 핵심 비즈니스 로직이 여기에 있겠구나라고 비즈니스 계층을 인식하는데 도움이 됨
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 {
}
}
includeFilters
에 MyIncludeComponent
annotation을 추가해서 BeanA가 스프링 빈에 등록됨excludeFilters
에 MyExcludeComponent
annotation을 추가해서 BeanB가 스프링 빈에 등록되지 않음org.example.SomeAnnotation
org.example.SomeClass
org.example..*Service+
org\.example\.Default.*
TypeFilter
라는 인터페이스를 구현해서 처리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)
}
)
@Component
만으로 충분하고, 최근 스프링 부트는 컴포넌트 스캔을 기본으로 제공하기 때문에 옵션을 변경하면서 사용하기 보다는 스프링 기본 설정에 최대한 맞추어 사용하는 것을 권장함ConflictingBeanDefinitionException
예외 발생...
@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
에 코드를 붙여넣으면 오버라이딩이 설정되면서 오류가 발생하지 않고 실행됨출처 : 스프링 핵심 원리 - 기본편