Why is this an issue?

Classes annotated as @Controller in Spring are responsible for handling incoming web requests. When annotating methods or the entire controller with @ResponseBody, the return value of said methods will be serialized and set as the response body. In other words, it tells the Spring framework that this method does not produce a view. This mechanism is commonly used to create API endpoints.

Spring provides @RestController as a convenient annotation to replace the combination of @Controller and @ResponseBody. The two are functionally identical, so the single annotation approach is preferred.

This rule will raise an issue on a class that is annotated with @Controller if:

How to fix it

Replace the @Controller annotation with the @RestController annotation and remove all @ResponseBody annotations from the class and its methods.

Code examples

Noncompliant code example

@Controller
@ResponseBody
public class MyController {
    @GetMapping("/hello")
    public String hello() {
        return "Hello World!";
    }
}

Compliant solution

@RestController
public class MyController {
    @GetMapping("/hello")
    public String hello() {
        return "Hello World!";
    }
}

Noncompliant code example

@Controller
public class MyController {
    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        return "Hello World!";
    }

    @ResponseBody
    @GetMapping("/foo")
    public String foo() {
        return "Foo";
    }
}

Compliant solution

@RestController
public class MyController {
    @GetMapping("/hello")
    public String hello() {
        return "Hello World!";
    }

    @GetMapping("/foo")
    public String foo() {
        return "Foo";
    }
}

Resources

Articles & blog posts