@Componentscan 어노테이션은 @Component어노테이션 및 streotype(@Service, @Repository, @Controller.)어노테이션이 부여된 Class들을 자동으로 Scan하여 Bean으로 등록해주는 역할을 하는 어노테이션입니다.
이전 xml파일에 <context:component-scan base-package="패키지 경로"/>를 이용해 지정해주었던 것을 Java파일을 이용하여 bean을 scan하기 위해서 생겨났습니다.
예제
1. 프로젝트 구조
Application Class : Main
ApplicationConfig Class: Bean설정을 어노테이션 기반으로 처리하기 위한 클래스
BookRepository Class: Bean으로 등록되기 위한 Class
2. Class
2.1 BookRepository
xxxxxxxxxxpublic class BookRepository {}Bean으로 등록되기 위한 클래스입니다. 상단에 @Repository 어노테이션을 부여하여 Bean으로 등록하기 위한 준비를 마쳤습니다.
2.2 ApplicationConfig
public class ApplicationConfig {}우선 @Configuration어노테이션을 이용하여 Bean 설정 파일(XML 파일을 대체하는)임을 알려주고, @ComponentScan어노테이션을 이용해 빈으로 등록되기 위한 어노테이션이 부여된 클래스들을 자동으로 IoC컨테이너에 등록하도록 했습니다.
2.3 Application
xxxxxxxxxxpublic class Application { public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfig.class); BookRepository repository = (BookRepository)context.getBean("bookRepository"); System.out.println(repository != null); }}== 결과 ==trueAnnotaion을 기반으로 Bean들을 등록하기 위해서는 AnnotaionConfigApplicationContext를 이용해야 합니다. AnnotationConfigApplicationContext의 매개변수로 Bean설정 클래스인 ApplicationConfig를 넘겨주었습니다.
ComponentScan의 범위
@ComponentScan 어노테이션은 Scan범위를 지정할 수 있습니다.
1. basePackages
xxxxxxxxxx(basePackages = "com.keesun.spring")public class ApplicationConfig {}basePackages의 경우 괄호안에 직접 패키지경로를 직접 적어주어 스캔할 위치를 지정할 수 있습니다. 이 경우 typesafe하지 않기 때문에 조금만 철자가 잘못되더라도 scan을 못하는 오류가 나타날 수 있습니다.
2. basePackageClasses
xxxxxxxxxx(basePackageClasses = Application.class)public class ApplicationConfig {}basePackageClasses의 경우에는 괄호안에 적힌 Class가 위치한 곳에서부터 모든 어노테이션이 부여된 Class를 빈으로 등록해줍니다. Class를 통해 기입하기 때문에 훨씬 Typesafe한 방법입니다.
'FrameWork > Spring' 카테고리의 다른 글
| Spring - IoC 컨테이너의 기능 - 1 (Bean의 Scope) (0) | 2019.04.11 |
|---|---|
| Spring - @Autowired 분석! (2) | 2019.04.10 |
| Spring - @(Annotation) 사용시 알 수 없는 에러 (0) | 2019.04.04 |
| Spring - 사용자가 전달한 값 사용하기 - 7 (Command 객체, @RequestParam, @PathVariable) - 7 (2) | 2019.04.03 |
| Spring - Model을 이용하여 View에 데이터 넘겨주기 - 6 (4) | 2019.04.03 |