Bird
0
0

Which of the following is the correct way to declare a REST controller class in Spring Boot?

easy📝 Syntax Q3 of 15
Spring Boot - REST Controllers
Which of the following is the correct way to declare a REST controller class in Spring Boot?
A<pre>@Controller public class MyController { public String test() { return "OK"; } }</pre>
B<pre>@RestController public class MyController { @GetMapping("/test") public String test() { return "OK"; } }</pre>
C<pre>@Service public class MyController { @GetMapping("/test") public String test() { return "OK"; } }</pre>
D<pre>@Repository public class MyController { @GetMapping("/test") public String test() { return "OK"; } }</pre>
Step-by-Step Solution
Solution:
  1. Step 1: Identify the correct annotation

    To create a REST controller, the class must be annotated with @RestController.
  2. Step 2: Check method mapping

    The method handling HTTP GET requests should be annotated with @GetMapping and return a response body.
  3. Step 3: Verify method signature

    The method returns a String which will be sent as the HTTP response body.
  4. Final Answer:

    @RestController
    public class MyController {
      @GetMapping("/test")
      public String test() {
        return "OK";
      }
    }
    correctly declares a REST controller with proper mapping and return type.
  5. Quick Check:

    Ensure @RestController and @GetMapping are used together [OK]
Quick Trick: Use @RestController with @GetMapping for REST endpoints [OK]
Common Mistakes:
  • Using @Controller without @ResponseBody for REST
  • Annotating with @Service or @Repository instead of @RestController
  • Missing @GetMapping on methods

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes