dev.jaieve 공부기록

[Spring] 스프링 stereotype 어노테이션 본문

Back/Springboot

[Spring] 스프링 stereotype 어노테이션

제이브 2022. 2. 20. 00:03

* 이 글은 howToDoInJava.com의 원문을 학습용으로 번역한 글로 잘못된 해석이 있을 수 있음을 사전에 알려드립니다!


1. Spring bean Stereotype Annotations

1.1 @Component 어노테이션

  • @Component 어노테이션은 Spring의 component-scanning 메커니즘에 의해 bean을 스프링컨테이너  ApplicationContext에 만들어 넣어준다.
@Component
public class EmployeeDAOImpl implements EmployeeDAO {
    ...
}

 

1.2 @Repository 어노테이션

@Component 의 기본 특성에 DAO에 특화된 추가적인 기능을 제공하는 어노테이션으로 기능은 @Component와 거의 유사하다. DI Container에 DAO를 넣을 뿐만 아니라, DAO의 메서드에 의해 던져진 exception을 DataAccessException으로 translate해준다.

public interface EmployeeDAO 
{
  public EmployeeDTO createNewEmployee();
}
 
@Repository ("employeeDao")
public class EmployeeDAOImpl implements EmployeeDAO
{
  public EmployeeDTO createNewEmployee()
  {
    EmployeeDTO e = new EmployeeDTO();
    e.setId(1);
    e.setFirstName("Lokesh");
    e.setLastName("Gupta");
    return e;
  }
}

1.3 @Service 어노테이션

  • @Component와 비교해봤을 때 다른 기능을 가지고 있지는 않지만, 의도를 명확히 밝힐 수 있기 때문에 service-layer 클래스에서 @Component를 대신하여 사용하는 어노테이션이다.
  • DI컨테이너에 service-lay 클래스의 bean을 특정 name을 명시하면서 주입하고 싶다면 다음과 같이 사용할 수 있다.
public interface EmployeeManager 
{
  public EmployeeDTO createNewEmployee();
}
 
@Service ("employeeManager")
public class EmployeeManagerImpl implements EmployeeManager
{
  @Autowired
  EmployeeDAO dao;
   
  public EmployeeDTO createNewEmployee()
  {
    return dao.createNewEmployee();
  }
}

1.4 @Controller 어노테이션

  • Spring Web MVC 컨트롤러에 사용되는 어노테이션으로 @Component의 기본 특성에 bean을 DI 컨테이너에 자동으로 주입해준다. @Controller를 사용하는 컨트롤러의 method에서는 @RequestMapping을 사용할 수 있게 된다. @RequestMapping은 method에 URL을 mapping해주는 기능을 한다.
@Controller ("employeeController")
public class EmployeeController 
{
        @Autowired
  EmployeeManager manager;
   
  public EmployeeDTO createNewEmployee()
  {
    return manager.createNewEmployee();
  }
}

 


 

2. 컴포넌트 스캔

스프링 프레임워크의 DI컨테이너가 위에서 소개한 4개의 어노테이션을 스캔하면 해당 어노테이션을 가진 class의 bean을 스캔하고 구성한다. 스캔을 하기위해서는 applicationContext.xml 파일에 “context:component-scan” 태그가 있어야한다.

<context:component-scan base-package="com.spring.hello.service" />
<context:component-scan base-package="com.spring.hello.dao" />
<context:component-scan base-package="com.spring.hello.controller" />

@Component 를 사용하면 위와 같이 component 감지 설정정보를 선언해주지 않아도 된다.

ℹ️ component-scan 태그가 있다면 컴포넌트 스캔이 가능할 때 빈을 자동으로 컨테이너로 주입해주기 때문에 context:annotation-config 는 태그는 없어도 된다.

 


 

3. @Component, @Repository, @Service and @Controller 어노테이션 사용

실제 개발시에는 DAO layer와 Manager(or Service) layer는 인터페이스와 클래스(구현체) 로 분리된 경우가 많다. 그럴 때 항상, 어노테이션은 인터페이스가 아닌 구현체 클래스에서 사용해주어야한다.

public interface EmployeeDAO
{
    //...
}
 
@Repository
public class EmployeeDAOImpl implements EmployeeDAO
{
    //...
}

 


 

4. @Component와 @Bean의 차이점

@Component 어노테이션은 classpath를 스캔하여 bean을 자동으로 감지하고 설정할 때 사용한다. 이는 하나의 클래스와 bean이 1:1로 mapping되는 것을 의미한다.(싱글톤..?)

@Bean 어노테이션은 Spring이 빈을 자동으로 선언하도록 두지않고, 해당 object를 하나의 bean으로 선언할 때 사용된다.

또 하나의 큰 차이점이 있다면 @Component는 class 수준의 annotation인 반면, @Bean은 method 수준의 annotation이며 기본적으로 method의 이름이 bean 이름으로 사용된다.

 


Reference

  1. https://howtodoinjava.com/spring-core/stereotype-annotations/
반응형