SERVER/SpringBoot

[SPRING BOOT] @Controller, @RestController 차이

eunoia07 2022. 6. 30. 18:45

전체 소스코드는 여기서 확인하실 수 있습니다 🎵

사전정보 - 어노테이션과 RESTful API


[ Spring Annotation ]

Spring 어노테이션은 프로그램에 대한 추가 정보를 제공하는데 사용합니다. 프로그램에 직접적인 영향은 미치지 않고 프로그램에 대한 데이터를 제공하는 메타데이터의 한 형태입니다.

 

😎 사람들이 코드를 볼 때 주석을 보고 해석을 하듯, 프로그램을 컴파일, 실행 할 때 어노테이션을 보고 참고해 코드를 해석한다고 생각하시면 됩니다.

 

Spring Framework는 아래와 같이 다양한 어노테이션을 제공하고 있습니다.

  • @Required
  • @Autowired
  • @Bean
  • @Component
  • @Controller
  • @Service
  • @Repository
  • etc ...

[ Spring REST API 워크플로 ]

Spring에서 REST API를 처리하는 방법은 아래와 같습니다.

1. DispatcherServlets는 요청을 받음

2. URI 요청을 처리하기 위해 핸들러에 매핑된 Controller 메서드 실행

3. Controller 메서드가 실행 된 후 반환된 리소스는 응답으로 처리

@Controller 어노테이션


@Controller 어노테이션은 @Component 어노테이션에서 발전한 것으로 특정 클래스가 컨트롤러 역할을 수행함을 표현할 때 사용합니다.

@Controller
@ResponseBody
@RequestMapping("/api/hello")
public class TreeController {

    @Autowired
    private TreeRepository repository;
 
    @GetMapping("/{id}")
    public Tree getTreeById(@PathVariable int id) {
        return repository.findById(id);
    }
  
    @GetMapping
    public Tree getTreeById(@RequestParam String name, 
                            @RequestParam int age) {
        return repository.findFirstByCommonNameIgnoreCaseAndAge(name, age);
    }
}

이제 DispatcherServlet는 요청이 들어오면 매핑된 메서드에 대해 Controller가 붙어있는 클래스를 검색할 수 있습니다. 클래스를 검색 한 후 RequestMapping 어노테이션을 통해 요청에 대해 어떤 Controller, 어떤 메소드가 처리할지를 맵핑합니다.

@RestController 어노테이션


@RestController는 RESTful 웹 서비스 생성을 단순화하기 위한 @Controller의 특수 버전으로@Controller + @ResponseBody으로 구성되어 결과적으로 컨트롤러 구현을 단순화합니다.

💡 @ResponseBody 어노테이션은 해당 메서드의 반환된 값이 자동으로 JSON으로 직렬화되고 HttpRespnse 객체로 전달되었음을 Controller에게 알려주는 역할을 합니다. 
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
  //..
}

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {
  //..
}

위 코드를 비교해 보면 RestController에 @ResponseBody 어노테이션이 미리 선언되어 있는 것을 확인할 수 있습니다.

@RestController
@RequestMapping("/api/hello")
public class TreeRestController {

    @Autowired
    private TreeRepository repository;
 
    @GetMapping("/{id}")
    public Tree getTreeById(@PathVariable int id) {
        return repository.findById(id);
    }
  
    @GetMapping
    public Tree getTreeById(@RequestParam String name, 
                            @RequestParam int age) {
        return repository.findFirstByCommonNameIgnoreCaseAndAge(name, age);
    }
}

맺으며 ••• 💫


이렇게 @Controller 어노테이션과 @RestController 어노테이션에 대해 알아봤습니다.

틀린문장이나 수정해야 할 부분은 댓글로 남겨주시면 감사하겠습니다🙏

[ 참고 ]

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/stereotype/Controller.html 
https://www.baeldung.com/spring-request-response-body
https://www.baeldung.com/spring-controller-vs-restcontroller
https://stackabuse.com/controller-and-restcontroller-annotations-in-spring-boot/