Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What is @RestController and how is it different from @Controller? @RestController क्या है और यह @Controller से कैसे अलग है?

Answer

@RestController is a convenience annotation that combines @Controller and @ResponseBody. It marks a class as a request handler where every method's return value is written directly to the HTTP response body, serialized as JSON or XML, instead of being resolved to a view name.

@Controller alone is used for traditional MVC apps that return view names (e.g., Thymeleaf templates); to return data directly from a @Controller method you would need to add @ResponseBody on every method. @RestController applies that behavior class-wide, which is why it's the standard choice for building REST APIs.

@RestController
@RequestMapping("/api/users")
public class UserController {
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        return userService.findById(id);
    }
}

@RestController एक कन्वीनियंस एनोटेशन है जो @Controller और @ResponseBody को मिलाता है। यह क्लास को एक ऐसे रिक्वेस्ट हैंडलर के रूप में चिह्नित करता है जहाँ हर मेथड का रिटर्न वैल्यू सीधे HTTP रिस्पॉन्स बॉडी में लिखा जाता है (JSON या XML के रूप में), न कि किसी व्यू नाम में रिज़ॉल्व होता है।

अकेले @Controller का उपयोग पारंपरिक MVC ऐप्स के लिए होता है जो व्यू नाम रिटर्न करते हैं; डेटा सीधे रिटर्न करने के लिए हर मेथड पर @ResponseBody जोड़ना पड़ता। @RestController यह व्यवहार पूरी क्लास पर लागू करता है, इसीलिए यह REST API बनाने के लिए मानक विकल्प है।

@RestController
@RequestMapping("/api/users")
public class UserController {
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        return userService.findById(id);
    }
}

Was this answer clear?