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.
-
@Controller
is used to mark classes as Spring MVC Controller. -
@RestController
is a convenience annotation that does nothing more than adding the@Controller
and@ResponseBody
annotations (see: Javadoc)
So the following two controller definitions should do the same
@Controller
@ResponseBody
public class MyController { }
@RestController
public class MyRestController { }
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.
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.