Learnitweb

@Controller and @RestController annotation in Spring

1. Introduction

In this tutorial, we’ll discuss the difference between @Controller and @RestController annotations in Spring MVC.

The @Controller annotation is available since Spring 2.5 whereas @RestController was introduced in Spring 4.0 to simplify creation of RESTful web services.

2. @Controller annotation

This annotation is a specialization of @Component and indicates that the annotated class is a controller, for example a web controller.

The classes annotated with @Controller can be autodetected through classpath scanning. We typically use @Controller in combination with a @RequestMapping annotation for request handling methods.

This annotation is in org.springframework.stereotype package.

@Target(value=TYPE)
 @Retention(value=RUNTIME)
 @Documented
 @Component
public @interface Controller

Following is a typical example of using @Controller annotation.

@Controller
@RequestMapping("firstController")
public class HelloController {

	@GetMapping(value = "/hello", produces = "application/json")
	public @ResponseBody String print() {
		return "hello";
	}
}

We have annotated the request handling method with @ResponseBody, which indicates a method return value should be bound to the web response body.

3. @RestController annotation

This annotation is available since Spring 4.0. The @RestController annotation is itself annotated with @Controller and @ResponseBody, so if you are using @RestController then you don’t need to use @Controller and @ResponseBody.

This controller is in org.springframework.web.bind.annotation package.

@Target(value=TYPE)
 @Retention(value=RUNTIME)
 @Documented
 @Controller
 @ResponseBody
public @interface RestController

When you annotate a class with @RestController then it is treated as Controller and @RequestMapping methods assume @ResponseBody semantics by default.

If a class is annotated with @RestController then @RequestMapping methods need not to be annotated with @RequestBody.

The controller which we wrote earlier can be rewritten using @RestController as:

@RestController
@RequestMapping("firstController")
public class HelloController {

	@GetMapping(value = "/hello", produces = "application/json")
	public String print() {
		return "hello";
	}
}

4. Conclusion

In this article, we discussed the @Controller and @RestController annotation and their difference.