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 {
}
@ComponenetScan : 스프링 빈을 일일이 등록하기 어렵거나 귀찮은 경우 @Component가 붙은 클래스를 스캔해서 스프링 빈으로 등록한다.
excludeFilters : CompontScan을 할 때 스캔에서 제외되는 것을 설정할 때 쓰며 Configuration 애너테이션 (@Configuration)이 붙은 클래스는 컴포넌트 스캔 대상에서 제외하도록 설정한다.
*** @Configuration이 붙으면 자동으로 컴포넌트도 붙어있기 때문에 (수동 등록) 컴포넌트 스캔을 할 때 제외를 안 해주면 이중으로 등록이 되어서 오류가 날 수 있다. ***
@Component
public class MemberServiceImpl implements MemberService {
private final MemberRepository memberRepository;
@Autowired
public MemberServiceImpl(MemberRepository memberRepository) {
this.memberRepository = memberRepository;
}
컴포넌트 스캔을 이용한 AutoAppConfig는 기존의 코드와 달리 의존관계 주입이 명시적으로 되어있지 않으므로
@Autowired를 생성자 코드쪽에 넣으면 스프링 컨테이너가 자동으로 해당 스프링 빈을 주입해 준다. (자동 의존성 주입)
해당 스프링 빈을 찾을 때는 타입이 같은 빈을 찾는다. (ex 상속 관계)
2. basePackages
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
@Configuration
@ComponentScan (
basePackages = "hello.core.member",
excludeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Configuration.class)
)
public class AutoAppConfig {
}
@ComponentScan 부분에 basePackages를 등록하면 컴포넌트 스캔을 할 곳을 지정할 수 있다.
만약 위 코드처럼 hello.core.member로 지정을 했다면 member 패키지에 있는 클래스만 컴포넌트 스캔을 하게 된다.
물론 탐색할 패키지를 여러 개도 할 수 있다.
ex) hello.core.member, hello.core.order
출처 : 인프런 - 스프링 핵심 원리(기본편)
'Spring > Spring' 카테고리의 다른 글
[Spring] 롬복 알아보기 (@RequiredArgsConstructor) (0) | 2024.09.04 |
---|---|
[Spring] 의존관계 주입 방법 (0) | 2024.09.03 |
[Spring] 싱글톤 패턴과 싱글톤 컨테이너 (0) | 2024.08.30 |
[Spring] BeanFacory와 ApplicationContext (0) | 2024.08.30 |
[Spring] 빈 조회하기 - 상속 관계 (1) | 2024.08.30 |