Home > AI > Backend > SpringBoot >

The difference between @Controller and @RestController

The @Controller is a specialization of @Component annotation while @RestController is a specialization of @Controller annotation. It is actually a convenience controller annotated with @Controller and @ResponseBody as shown below.

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

and here is how the declaration of @Controller looks like:

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

You can see that if you use Spring MVC @Controller annotation to create a RESTful response you need to annotate each method with the @ResponseBody annotation, which is not required when you use @RestController. It not only makes your code more readable but also saves a couple of keystrokes for you.

Leave a Reply