새발블로그
[Spring] Component Scan (컴포넌트 스캔) 본문
컴포넌트 스캔이란?
스프링이 특정 패키지를 탐색하면서, @Component 계열 어노테이션이 붙은 클래스를 자동으로 Bean으로 등록하는 기능
작동 원리
- @ComponentScan 선언
- 내부적으로 ClassPathScanningCandidateComponentProvider가 클래스 경로 탐색
- @Component, @Service 등 등록 대상 클래스 찾음
- Spring Container에 Bean으로 등록
대상 어노테이션
| 어노테이션 | 설명 |
| @Component | 기본 컴포넌트 |
| @Service | 서비스 계층 |
| @Repository | DAO 계층 |
| @Controller | MVC 컨트롤러 |
설정 방법
Java 기반 설정
@Configuration
@ComponentScan(basePackages = "com.example")
public class AppConfig {}
XML 기반 설정
<context:component-scan base-package="com.example" />
Bean 이름 규칙
클래스 이름의 카멜 케이스를 따른다.
@Component
public class BookService {}
→ Bean 이름: bookService
필요 시 @Component("이름")으로 명시 가능
필터 포함/제외 방법
@ComponentScan(
includeFilters = @Filter(type = FilterType.ANNOTATION, classes = MyAnnotation.class),
excludeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = LegacyService.class)
)
- 특정 클래스/어노테이션 기준으로 포함하거나 제외 가능
- 유지보수 편의성 위해 과도한 필터 사용은 지양
'Server > Spring' 카테고리의 다른 글
| [Spring] Bean Scope & 생명주기 (0) | 2025.07.08 |
|---|---|
| [Spring] 의존성 주입 (Dependency Injection) (0) | 2025.07.08 |
| [Spring] Bean 등록 방식 (수동 vs 자동) (0) | 2025.07.08 |
| [Spring] Spring Container 스프링 컨테이너 (0) | 2025.07.06 |
| [Spring] FrontController (0) | 2025.07.06 |