본문 바로가기
개발&프로그래밍

[Spring] @Controller 과 @RestController 어노테이션

by 재아군 2022. 3. 14.

Spring MVC에서 @Controller와 @RestController 어노테이션의 차이점에 대해 알아봅니다.

 

 

@RestController 어노테이션은 Spring 4.0 에서 새롭게 추가가 되었습니다. 기존의 @Controller와 @ResponseBody를 결합한 어노테이션으로 모든 요청 처리에 대해 @ResponseBody를 추가할 필요가 없습니다.

 

@Controller을 사용

package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("users")
public class UserController {
    @GetMapping(name="/{id}", produces = "application/json")
    public @ResponseBody User getUser(@PathVariable String id) {
        return findUserById(id);
    }

    private User findUserById(String id) {
        // ...
        return user;
    }

}

 

@RestController

package com.example.demo;

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("users")
public class UserController {
    @GetMapping(name="/{id}", produces = "application/json")
    public User getUser(@PathVariable String id) {
        return findUserById(id);
    }

    private User findUserById(String id) {
        // ...
        return user;
    }
}

RestController를 사용하면 @ResponseBody 어노테이션이 필요하지 않습니다. 컨트롤러 클래스의 모든 요청 처리 메서드는 자동으로 반환 개체를 HttpResponse 로 직렬화합니다 .

 


 

RestController 어노테이션을 살펴보면 @Controller와 @ResponseBody 어노테이션이 포함되어있어서 컨트롤러의 구현을 단순화합니다.

package org.springframework.web.bind.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
import org.springframework.stereotype.Controller;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
    @AliasFor(
        annotation = Controller.class
    )
    String value() default "";
}

댓글