[java] Difference between spring @Controller and @RestController annotation

Difference between spring @Controller and @RestController annotation.

Can @Controller annotation be used for both Web MVC and REST applications?
If yes, how can we differentiate if it is Web MVC or REST application.

This question is related to java spring spring-mvc

The answer is


As you can see in Spring documentation (Spring RestController Documentation) Rest Controller annotation is the same as Controller annotation, but assuming that @ResponseBody is active by default, so all the Java objects are serialized to JSON representation in the response body.


In the code below I'll show you the difference between @controller

@Controller
public class RestClassName{

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

and @RestController

@RestController
public class RestClassName{

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

the @ResponseBody is activated by default. You don't need to add it above the function signature.


@RestController is the combination of @Controller and @ResponseBody.

Flow of request in a @Controller class without using a @ResponseBody annotation:

enter image description here

@RestController returns an object as response instead of view.

enter image description here


Actually, be careful - they are not exactly the same.

If you define any interceptors within your application, they will not apply to Controllers annotated as @RestController, however they do work with @Controller annotated controllers.

ie. configuration for the interceptor:

@Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {


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

}

and in the declaration of a Spring controller:

@Controller
public class AdminServiceController {...

Will work, however

@RestController
public class AdminServiceController {...

does not end up having the interceptor being associated with it.


@RestController was provided since Spring 4.0.1. These controllers indicate that here @RequestMapping methods assume @ResponseBody semantics by default.

In earlier versions the similar functionality could be achieved by using below:

  1. @RequestMapping coupled with @ResponseBody like @RequestMapping(value = "/abc", method = RequestMethod.GET, produces ="application/xml") public @ResponseBody MyBean fetch(){ return new MyBean("hi") }

  2. <mvc:annotation-driven/> may be used as one of the ways for using JSON with Jackson or xml.

  3. MyBean can be defined like

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

  1. @ResponseBody is treated as the view here among MVC and it is dispatched directly instead being dispatched from Dispatcher Servlet and the respective converters convert the response in the related format like text/html, application/xml, application/json .

However, the Restcontroller is already coupled with ResponseBody and the respective converters. Secondly, here, since instead of converting the responsebody, it is automatically converted to http response.


The @Controller annotation indicates that the class is a "Controller" like a web controller while @RestController annotation indicates that the class is a controller where @RequestMapping methods assume @ResponseBody semantics by default i.e. servicing REST API


THE new @RestController annotation in Spring4+, which marks the class as a controller where every method returns a domain object instead of a view. It’s shorthand for @Controller and @ResponseBody rolled together.


  • @Controller: This annotation is just a specialized version of @Component and it allows the controller classes to be auto-detected based on classpath scanning.
  • @RestController: This annotation is a specialized version of @Controller which adds @Controller and @ResponseBody annotation automatically so we do not have to add @ResponseBody to our mapping methods.

@Controller is used in legacy systems which use JSPs. it can return views. @RestController is to mark the controller is providing REST services with JSON response type. so it wraps @Controller and @ResponseBody annotations together.


@Controller returns View. @RestController returns ResponseBody.


@RestController is composition of @Controller and @ResponseBody, if we are not using the @ResponseBody in Method signature then we need to use the @Restcontroller.


Instead of using @Controller and @ResponseBody, @RestController let's you expose Rest APIs in Spring 4.0 and above.


If you use @RestController you cannot return a view (By using Viewresolver in Spring/springboot) and yes @ResponseBody is not needed in this case.

If you use @Controller you can return a view in Spring web MVC.


@RestController annotated classes are the same as @Controller but the @ResponseBody on the handler methods are implied.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to spring

Are all Spring Framework Java Configuration injection examples buggy? Two Page Login with Spring Security 3.2.x Access blocked by CORS policy: Response to preflight request doesn't pass access control check Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Spring Data JPA findOne() change to Optional how to use this? After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName The type WebMvcConfigurerAdapter is deprecated No converter found capable of converting from type to type

Examples related to spring-mvc

Two Page Login with Spring Security 3.2.x ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized The type WebMvcConfigurerAdapter is deprecated RestClientException: Could not extract response. no suitable HttpMessageConverter found Spring boot: Unable to start embedded Tomcat servlet container UnsatisfiedDependencyException: Error creating bean with name 8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)