Junior — Middle
How to implement a REST controller in Spring using the @RestController annotation?
sobes.tech AI
Answer from AI
A Spring REST controller is created using the @RestController annotation, which combines @Controller and @ResponseBody. This allows for automatic serialization of returned objects into JSON or other formats.
Example of a simple REST controller:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, world!";
}
}
In this example, when accessing /hello, the client will receive the string "Hello, world!" in the response body. You can also return objects, which Spring will automatically convert to JSON.