본문 바로가기

프로그래밍/Spring

[Spring]@Component 자동 스캔

@Component 

- @Component 어노테이션을 사용하려면 설정파일에 <context:component-scan base-package="패키지명"> 으로 태그를 지정

- 해당 패키지에서 @Component 어노테이션이 적용된 클래스를 검색하여 빈으로 자동 등록

- 자동 등록된 빈의 아이디는 클래스 이름의 첫글자를 소문자로 바꿔서 사용 (HelloController -> helloController)

- 빈 이름 지정하고 싶을 떄는 @Component("hello")와 같이 명시하거나

@Component
@named("hello")

도 가능하다.

1
2
3
4
5
    <!-- 컨테이너에 빈을 등록하기 위해서 패키지 지정 -->
    <context:component-scan base-package="kr.spring.ch05"/>
    
    <!-- <context:component-scan/>를 사용하면 아래 명시한 <context:annotation-config/>는 생략 가능 -->
    <!-- <context:annotation-config/> -->
cs

- xml  설정 파일

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Component
public class HomeController {
    @Autowired
    private Camera camera;
 
    public void setCamera(Camera camera) {
        this.camera = camera;
    }
 
    @Override
    public String toString() {
        return "HomeController [camera=" + camera + "]";
    }
}
cs