This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

Question: The difference between the @Controller and @restController annotations in Spring

The difference between the @Controller and @restController annotations in Spring

Can both Web MVC and REST Applications use @Controller? If so, how do you distinguish between a Web MVC and a REST Application

Answer a

The following code shows you the difference between @Controller and @RestController

Copy the code
@Controller
public class RestClassName{

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

Copy the code
@RestController
public class RestClassName{

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

@responseBody is activated by default. You don’t have to put that in the method declaration.

Answer two

  • @Controller is used to mark the class as Spring MVC Controller
  • @restController is a handy annotation with @Controller and @responseBody (see Javadoc)

So the two controllers defined below should be the same

@Controller
@ResponseBody
public class MyController {}@RestController
public class MyRestController {}Copy the code

Answer three

In fact, be careful, they’re not exactly the same

If your application defines any Interceptors, they do not apply to Controllers that are annotated with @Controllers, but they do apply to Controllers that are annotated with @Controller.

Interceptor configuration:

@Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {


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

Declare a Spring Controller:

@Controller
public class AdminServiceController {...
Will work, however

@RestController
public class AdminServiceController {...
Copy the code

Eventually there is no interceptor associated with it

Answer four

As you can see in Spring RestController Documentation, the RestController annotation is the same as the Controller annotation, but @responseBody is in effect by default, So all Java objects are serialized to JSON format in the response body.

Answer five

The new annotation @restcontroller in Spring4 and above marks the class as a controller, where each method returns an object instead of a view. It’s a combination of @Controller and @ResponseBody.

The article translated from Stack Overflow:stackoverflow.com/questions/2…