728x90

이 글은 인프런에서 김영한 님의 "스프링 핵심원리 - 기본편"을 수강 후 공부한 내용을 정리한 게시글입니다. 부족한 부분이 있다면 언제든 지적 부탁드립니다.
✏️ 자동으로 스프링 빈을 등록해 → 컴포넌트 스캔(@ComponentScan, @Component)
컴포넌트 스캔이란 ?
- 지금까지의 과정에서 자바 코드의 @Bean 이나 XML의 <bean> 를 통해서 직접 스프링 빈을 등록
- 상당히 귀찮고 누락할 수 있는 가능성이 높다는 문제점을 지닌다.
- 이를 해결하기 위해 컴포넌트 스캔이라는 기능을 통해서 스프링 빈을 자동으로 등록할 수 있다.
컴포넌트 스캔 사용하기
- 컴포넌트 스캔을 사용하려면 먼저 @ComponentScan 을 설정 클래스에 붙여준다.
- 기존의 AppConfig와는 다르게 @Bean으로 등록한 클래스가 하나도 없다!
AutoAppConfig.java
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
public class AutoAppConfig {
}
- 컴포넌트 스캔은 @Component 어노테이션이 붙은 클래스를 스캔해서 스프링 빈으로 등록한다.
- 그래서 스프링 빈으로 등록하고 싶은 클래스를 컴포넌트 스캔의 대상이 되도록 @Component 어노테이션을 붙여주자.
MemoryMemberRepository.java
@Component
public class MemoryMemberRepository implements MemberRepository {}
RateDiscountPolicy.java
@Component
public class RateDiscountPolicy implements DiscountPolicy {}
MemberServiceImpl.java
@Component
public class MemberServiceImpl implements MemberService {
private final MemberRepository memberRepository;
@Autowired
public MemberServiceImpl(MemberRepository memberRepository) {
this.memberRepository = memberRepository;
}
}
✏️ 의존관계 자동 주입(@Autowired)
- @Autowired 는 의존관계를 자동으로 주입해준다
OrderServiceImpl.java
@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 를 사용하면 생성자에서 여러 의존관계도 한번에 주입받을 수 있다
✏️ 컴포넌트 스캔과 자동 의존관계 주입의 동작 과정
- @ComponentScan
- @ComponentScan 은 @Component 가 붙은 모든 클래스를 스프링 빈으로 등록한다.
- 이때 스프링 빈의 기본 이름은 클래스명을 사용하되 맨 앞글자만 소문자를 사용한다.
- 빈 이름 기본 전략: MemberServiceImpl 클래스 memberServiceImpl
- @Autowired 의존관계 자동 주입
- 생성자에 @Autowired 를 지정하면, 스프링 컨테이너가 자동으로 해당 스프링 빈을 찾아서 주입한다.
- 기본 조회 전략은 타입이 같은 빈을 찾아서 주입한다.
✏️ 탐색 위치와 기본 스캔 대상
탐색할 패키지의 시작 위치 지정
- 모든 자바 클래스를 다 컴포넌트 스캔하면 시간이 오래 걸린다. 그래서 꼭 필요한 위치부터 탐색하도록 시작 위치를 지정할 수 있다.
@ComponentScan(basePackages = "hello.core",}
- basePackages : 탐색할 패키지의 시작 위치를 지정한다. 이 패키지를 포함해서 하위 패키지를 모두 탐색한다.
- basePackages = {"hello.core", "hello.service"} 이렇게 여러 시작 위치를 지정할 수도 있다.
- basePackageClasses : 지정한 클래스의 패키지를 탐색 시작 위치로 지정한다.
- 만약 지정하지 않으면 @ComponentScan 이 붙은 설정 정보 클래스의 패키지가 시작 위치가 된다.
- 설정 정보 클래스의 위치를 프로젝트 최상단에 두는 것을 권장.최근 스프링 부트도 이 방법을 기본으로 제공한다.
- 스프링 부트를 사용하면 스프링 부트의 대표 시작 정보인 @SpringBootApplication 를 이 프로젝트 시작 루트 위치에 두는 것이 관례이다. (그리고 이 설정안에 바로 @ComponentScan 이 들어있다!)
컴포넌트 스캔 기본 대상
컴포넌트 스캔은 @Component 뿐만 아니라 다음과 내용도 추가로 대상에 포함한다.
- @Controller : 스프링 MVC 컨트롤러로 인식
- @Service : 사실 @Service 는 특별한 처리를 하지 않는다. 대신 개발자들이 핵심 비즈니스 로직이 여기에 있겠구나 라고 비즈니스 계층을 인식하는데 도움이 된다
- @Repository : 스프링 데이터 접근 계층으로 인식하고, 데이터 계층의 예외를 스프링 예외로 변환해준다.
- @Configuration : 앞서 보았듯이 스프링 설정 정보로 인식하고, 스프링 빈이 싱글톤을 유지하도록 추가 처리를 한다.
사실 애노테이션에는 상속관계라는 것이 없다. 그래서 이렇게 애노테이션이 특정 애노테이션을 들고 있는 것을 인식할 수 있는 것은 자바 언어가 지원하는 기능은 아니고, 스프링이 지원하는 기능이다.
✏️ 중복 등록과 충돌
자동 빈 등록 vs 자동 빈 등록
- 컴포넌트 스캔에 의해 자동으로 스프링 빈이 등록되는데, 그 이름이 같은 경우 스프링은 오류를 발생시킨다.
- ConflictingBeanDefinitionException 예외 발생
수동 빈 등록 vs 자동 빈 등록
- 수동 빈 등록이 우선
- 수동 빈이 자동 빈을 오버라이딩
✏️ 다양한 의존관계 주입 방법
생성자 주입
- 생성자를 통해서 의존관계를 주입 받음
- 특징
- 생성자 호출 시점에 딱 1번만 호출됨이 보장
- 불변, 필수 의존관계에서 사용
- 생성자가 딱 1개만 있으면 @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;
}
}
수정자 주입(setter 주입)
- setter 메소드(수정자 메소드)를 통해서 의존관계를 주입 받음
- 특징
- 자바빈 프로퍼티 규약의 수정자 메소드 방식을 사용하는 방법
- 선택, 변경 가능성이 있는 의존관계에서 사용
- @Autowired 의 기본 동작은 주입할 대상이 없으면 오류가 발생한다. 주입할 대상이 없어도 동작하게 하려면 @Autowired(required = false) 로 지정하면 된다.
@Component
public class OrderServiceImpl implements OrderService {
private MemberRepository memberRepository;
private DiscountPolicy discountPolicy;
@Autowired
public void setMemberRepository(MemberRepository memberRepository) {
this.memberRepository = memberRepository;
}
@Autowired
public void setDiscountPolicy(DiscountPolicy discountPolicy) {
this.discountPolicy = discountPolicy;
}
}
필터 주입
- 필드에 바로 주입
- 특징
- 코드가 간결하지만 외부에서 변경이 불가능해서 테스트하기 어려움
- DI 프레임워크가 없으면 아무것도 할 수 없다.
- 사용하지 말자!!!!
- 어플리케이션의 실제 코드와 관계없는 테스트 코드가 생성됨
- 스프링 설정을 목적으로 하는 @Configuration 같은 곳에서만 특별한 용도로 사용하자.
@Component
public class OrderServiceImpl implements OrderService {
@Autowired
private MemberRepository memberRepository;
@Autowired
private DiscountPolicy discountPolicy;
}
일반 메소드 주입
- 일반 메소드를 통해서 주입
- 특징
- 한번에 여러번 필드를 주입받을 수 있다.
- 일반적으로 잘 사용하지 않음
@Component
public class OrderServiceImpl implements OrderService {
private MemberRepository memberRepository;
private DiscountPolicy discountPolicy;
@Autowired
public void init(MemberRepository memberRepository, DiscountPolicy
discountPolicy) {
this.memberRepository = memberRepository;
this.discountPolicy = discountPolicy;
}
}
반응형
'Programming > Spring' 카테고리의 다른 글
[Spring] 빈 생명주기 콜백 (0) | 2025.03.26 |
---|---|
[Spring] 의존관계 자동 주입2 (0) | 2025.03.26 |
[Spring] 싱글톤 컨테이너 (0) | 2025.03.26 |
[Spring] 스프링 컨테이너와 스프링 빈 (0) | 2025.03.26 |
[Spring] 스프링의 핵심 원리 이해2 - 객체 지향 원리 적용 (0) | 2025.03.26 |