Spring

[Spring] @Component, @ComponentScan 어노테이션

재담 2022. 2. 13. 22:32

컴포넌트 스캔을 이용한 빈 자동 등록

스프링은 특정 패키지 또는 그 하위 패키지에서 클래스를 찾아 스프링 빈으로 등록해주는 기능을 제공하고 있다. 이때 검색 대상은 @Component 어노테이션이 붙은 클래스이다. 다음 코드를 보자.

package com.mypackage;

@Component()
public class OrderService {
    // 이하 생략
    ...
}

@Component
public class ProductService {
    // 이하 생략
    ...
}

 

com.mypackage 패키지에 속한 두 클래스에 @Compnent 어노테이션을 적용하였다. @Component 어노테이션을 적용했다면, <context:component-scan> 태그를 이용해서 스프링이 클래스를 검색할 패키지를 지정하면 된다.

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">

   <context:component-scan base-package="com.mypackage"></context:component-scan>
   
   <!--이하 생략-->
   ...
</beans>

 

<context:component-scan> 태그는 base-package 속성에 지정한 패키지 및 그 하위 패키지에 위치한 클래스 중에서 @Component 어노테이션이 적용된 클래스를 검색해서 스프링 빈으로 등록한다. 자바 설정을 사용하고 있다면, @ComponentScan 어노테이션을 사용하면 된다.

@Configuration
@ComponentScan(basePackages = "com.mypackage")
public class ConfigScan {
    // 이하 생략
    ...
}

 

만약 특정한 이름을 명시해주고 싶다면 다음과 같이 어노테이션의 속성에 빈의 이름을 입력하면 된다. 이때 지정한 이름이 getBean 메서드로 빈을 가져올 때 첫 번째 인자 값이 된다. 이름을 지정하지 않으면 클래스의 첫 글자를 소문자로 바꾼 이름을 빈의 이름으로 사용한다.

@Component("orderSvc")
public class OrderService {
    // 이하 생략
    ...
}

Reference

  • 웹 개발자를 위한 Spring 4.0 프로그래밍 (최범균 저)