스프링 @Controller와 @RestController 주석의 차이점


356

봄 @Controller과 봄의 차이@RestController 주석의 .

@ControllerWeb MVC 및 REST 애플리케이션 모두에 주석을 사용할 수 있습니까 ?
그렇다면 Web MVC 또는 REST 응용 프로그램인지 어떻게 구별 할 수 있습니까?

답변:


471
  • @Controller 클래스를 Spring MVC Controller로 표시하는 데 사용됩니다.
  • @RestController@Controller및 @ResponseBody주석을 추가하는 것 이상을 수행하지 않는 편리한 주석입니다 ( Javadoc 참조 ).

따라서 다음 두 컨트롤러 정의는 동일하게 수행되어야합니다.

@Controller
@ResponseBody
public class MyController { }

@RestController
public class MyRestController { }


48
@RestController는 응답을 JSON / XML로 자동 변환한다고 생각합니다.
— arnabkaycee


9
당신이 템플릿 엔진을 사용하는 경우 또한 같은 Thymeleaf그것은 작동하지 않습니다 @RestController들 때문에 @ResponseBody하는이 주석에 포함되어 있습니다.
— Sonique

3
@ResponseBody예를 들어 JSON 또는 XML ( source ) 과 같이 본문에있을 수있는 객체로 반환 된 객체 만들기
— Martin Thoma

59

아래 코드에서 차이점을 보여 드리겠습니다. @controller

@Controller
public class RestClassName{

  @RequestMapping(value={"/uri"})
  @ResponseBody
  public ObjectResponse functionRestName(){
      //...
      return instance
   }
}

과 @RestController

@RestController
public class RestClassName{

  @RequestMapping(value={"/uri"})
  public ObjectResponse functionRestName(){
      //...
      return instance
   }
}

은 @ResponseBody기본적으로 활성화됩니다. 함수 서명 위에 추가하지 않아도됩니다.


1
Java의 클래스 이름은 대문자로 시작해야합니다 (예 : restClassName이 아닌 RestClassName).
— Razzle

24

사용 @RestController하면보기를 반환 할 수 없습니다 ( ViewresolverSpring / springboot에서 사용 )@ResponseBody 경우 예가 필요하지 않습니다.

사용 @Controller하면 Spring web MVC에서보기를 반환 할 수 있습니다.


예, @ResponseBody를 메소드에 넣을 수 있으며 리턴 유형을 HTTP 응답 본문에 직접 작성해야하며 모델에 배치하거나 뷰 이름으로 해석하지 않아야 함을 나타냅니다.
— PraveenKumar Lalasangi


14

실제로, 조심하십시오-정확히 동일하지는 않습니다.

당신이 당신의 응용 프로그램 내에서 모든 인터셉터를 정의하면, 그들은 같은 주석 컨트롤러에 적용되지 않습니다 @RestController하지만 그들은 함께 일을,@Controller 달린 컨트롤러 합니다.

즉. 인터셉터 구성 :

@Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new TemplateMappingInterceptor()).addPathPatterns("/**", "/admin-functions**").excludePathPatterns("/login**");
    }

}

스프링 컨트롤러 선언에서 :

@Controller
public class AdminServiceController {...

그러나 작동합니다

@RestController
public class AdminServiceController {...

인터셉터와 연관되지 않습니다.


2
@RestControllerSpring 4x에서 소개되었습니다. 이 주석은 또한 자체적으로 주석을 달았 @Controller으므로 작동하지 않으면 @Controller버그로보고하십시오.
— gaoagong

@ bertybro, 그건 옳지 않습니다. 당신은 연결할 수 있습니다 InterceptorA를 @RestController.
— Ravi-A-Doer

에를 성공적으로 첨부 Interceptor했습니다 @RestController.
— 벤 Barden

11

Spring 문서 ( Spring RestController Documentation ) 에서 볼 수 있듯이 Rest Controller 주석은 Controller 주석과 동일하지만 @ResponseBody가 기본적으로 활성화되어 있다고 가정하면 모든 json이 Java 객체로 구문 분석됩니다.


4

Spring4 +의 새로운 @RestController 주석은 클래스를 컨트롤러로 표시하여 모든 메소드가 뷰 대신 도메인 객체를 반환합니다. @Controller와 @ResponseBody의 줄임말입니다.


3

@RestControllerSpring 4.0.1부터 제공되었습니다. 이 컨트롤러 는 여기서 @RequestMapping 메소드가 기본적으로 @ResponseBody 의미론을 가정 함을 나타냅니다.

이전 버전에서는 다음을 사용하여 유사한 기능을 수행 할 수 있습니다.

  1. @RequestMapping과 함께 @ResponseBody같은@RequestMapping(value = "/abc", method = RequestMethod.GET, produces ="application/xml") public @ResponseBody MyBean fetch(){ return new MyBean("hi") }

  2. <mvc:annotation-driven/> Jackson 또는 xml과 함께 JSON을 사용하는 방법 중 하나로 사용될 수 있습니다.

  3. MyBean은 다음과 같이 정의 할 수 있습니다

@XmlRootElement(name = "MyBean") @XmlType(propOrder = {"field2", "field1"}) public class MyBean{ field1 field2 .. //getter, setter }

  1. @ResponseBody 여기서는 MVC에서보기로 취급되며 대신 Dispatcher Servlet에서 발송되는 대신 각 발송자가 text / html, application / xml, application / json과 같은 관련 형식으로 응답을 변환합니다.

그러나 Restcontroller는 이미 ResponseBody 및 해당 변환기와 연결되어 있습니다. 두 번째로 응답 본문을 변환하는 대신 자동으로 http 응답으로 변환됩니다.


2

@Controller을 반환합니다 View. @RestController을 반환합니다 ResponseBody.


2
더 설명해야합니다. 이것이 어떻게 질문에 대답합니까?
— Yunnosch

@Yunnosch 'view'는 jsp 또는 html과 같은 프론트 엔드입니다. ResponseBody는 xml, json, yaml 일 수 있습니다
— G.Brown

제발 편집 유용한 정보를 추가 답변을. 그러나 나는 여전히 질문에 어떻게 대답 해야하는지 알지 못한다. "예. 가능합니다 / 아니오 .. ...."라고 설명 할 수 있습니까?
— Yunnosch

1

@RestController 주석은 RESTful 웹 서비스 작성을 단순화하기 위해 Spring 4.0에 도입되었습니다. @Controller와 @ResponseBody를 결합한 편리한 주석으로, 컨트롤러 클래스의 모든 요청 처리 방법에 @ResponseBody 주석을 주석 처리 할 필요가 없습니다.


0
  • @Controller:이 주석은 특수화 된 버전이며 @Component클래스 경로 스캔을 기반으로 컨트롤러 클래스를 자동 감지 할 수 있습니다.
  • @RestController:이 주석은 특수한 버전 으로 자동으로 @Controller추가 @Controller되고 @ResponseBody주석 이 추가 되므로 @ResponseBody매핑 방법 에 추가 할 필요가 없습니다 .

0

@Controller는 JSP를 사용하는 레거시 시스템에서 사용됩니다. 뷰를 반환 할 수 있습니다. @RestController는 컨트롤러가 JSON 응답 유형으로 REST 서비스를 제공하고 있음을 표시합니다. @Controller와 @ResponseBody 주석을 함께 래핑합니다.


-3

@RestController의 구성입니다 @Controller그리고 @ResponseBody우리가 사용하지 않는 경우, @ResponseBody메소드 서명에 우리가를 사용해야합니다 @Restcontroller.


-3

@Controller와 @ResponseBody를 사용하는 대신 @RestController를 사용하면 Spring 4.0 이상에서 Rest API를 노출 할 수 있습니다.


당신이 말하고 싶은 나는 @RestController가 자동으로 JSON / XML에 대한 응답을 변환 생각합니다. ? 당신은 그것을 명확하게 설명하는 대신 추상 문장을 사용했습니다. 나는 그것을 제안하지 않을 것입니다.
— cinqS

생각해 보면 @Controller는 JSON / XML 또는 MIME 유형을 생성하고 소비하는 것과 동일하게 작동합니다. RestController는 암시 적으로 그렇게합니다.
— CoffeeBeanie
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.