@ComponentScan은 스프링 프레임워크에서 컴포넌트 클래스들을 찾아 빈으로 등록하는 역할을 하는 어노테이션입니다.
@Component, @Service, @Repository, @Controller 등의 어노테이션이 붙은 클래스를 찾아 빈으로 등록합니다.기본적인 사용 방법은 다음과 같습니다:
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "com.example.myapp")
public class AppConfig {
// 구성 내용
}
@Component를 메타 어노테이션으로 사용하는 모든 어노테이션(@Service, @Repository 등)을 인식합니다.@ComponentScan(basePackages = {"com.example.package1", "com.example.package2"})
@ComponentScan(basePackageClasses = MyClass.class)
@ComponentScan(includeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = MyService.class))
@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Exclude.class))
@ComponentScan은 기본적으로 다음 어노테이션이 붙은 클래스를 스캔 대상으로 합니다:
@Component@Service@Repository@Controller@Configuration사용자 정의 필터를 만들어 더 복잡한 스캔 로직을 구현할 수 있습니다:
public class CustomTypeFilter implements TypeFilter {
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
// 커스텀 로직 구현
}
}
@Configuration
@ComponentScan(includeFilters = @ComponentScan.Filter(type = FilterType.CUSTOM, classes = CustomTypeFilter.class))
public class AppConfig {
// 구성 내용
}
스프링 부트에서는 @SpringBootApplication 어노테이션이 @ComponentScan을 포함하고 있어, 별도로 지정하지 않아도 기본적인 컴포넌트 스캔이 이루어집니다.
@SpringBootApplication // @ComponentScan을 포함
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
@ComponentScan의 동작을 테스트할 때는 @ContextConfiguration을 사용할 수 있습니다:
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = AppConfig.class)
public class ComponentScanTest {
@Autowired
private ApplicationContext context;
@Test
public void testComponentScan() {
assertTrue(context.containsBean("myService"));
// 기타 검증 로직
}
}
@ComponentScan은 스프링의 강력한 자동 구성 기능의 핵심입니다. 이를 통해 개발자는 반복적인 빈 등록 작업에서 벗어나 비즈니스 로직에 더 집중할 수 있습니다. 그러나 효과적으로 사용하기 위해서는 애플리케이션의 구조를 잘 이해하고, 적절한 스캔 범위와 필터를 설정하는 것이 중요합니다.