Spring @Controller and @RestController Spring @Controller and @RestController

Page content

In this quick article, we’ll see @Controller and @RestController annotations and their difference in Spring MVC.

@Controller

@Component
public @interface Controller {

	@AliasFor(annotation = Component.class)
	String value() default "";

}

If you look at the above @Controller annotation definition, you will find out that it just a stereotype version of @Component annotation which is used to annotate class as a Spring Controller. It is mainly a controller part of Spring MVC (model-view-controller) Web application. It’s been there since the evolution of Spring Framework.

@Controller annotation typically used at class level in combination with a @RequestMapping annotation at method level to handle web requests.

@Controller
@RequestMapping("/users")
public class UserController {

	@GetMapping("/{id}", produces = "application/json")
	public @ResponseBody getUser(@PathVariable int id) {
		return getUserById(id);
	}

	private User getUserById(int id){
		// ...
	}
}

The request handling method is annotated with @ResponseBody. This annotation enables automatic serialization of the return object into the HttpResponse.

@RestController

@Controller
@ResponseBody
public @interface RestController {

	@AliasFor(annotation = Controller.class)
	String value() default "";

}

If you look at the above @RestController annotation definition, you will find out that it is an advance version of @Controller which includes both the @Controller and @ResponseBody annotations and as a result, simplifies the controller implementation such that now @ResponseBody isn’t required.

@RestController
@RequestMapping("/users")
public class UserController {

	@GetMapping("/{id}", produces = "application/json")
	public getUser(@PathVariable int id) {
		return getUserById(id);
	}

	private User getUserById(int id){
		// ...
	}
}

Every request handling method of the controller class automatically serializes return objects into HttpResponse.

@Controller vs @RestController

@Controller @RestController
Added in Spring 2.5 version Relatively new, added in Spring 4.0 version
Stereotype version of @Component Specialized version of @Controller
Required @ResponseBody on method handler @ResponseBody is not required as it is @Controller + @ResponseBody
Traditional way to create Spring MVC Controller Preferred way to use in RESTFul Web Services