RestController annotation with example
The `@RestController` annotation in Spring Boot is a specialized version of the `@Controller` annotation. It combines `@Controller` and `@ResponseBody`, eliminating the need to annotate every request handling method with `@ResponseBody`.
When you use `@RestController`, Spring assumes that the methods in this class will return data (usually in the form of JSON or XML) directly to the client, rather than returning a view name to be resolved.
Table of Contents
Example
Step 1: Create a Spring Boot Application
Ensure you have the necessary dependencies in your `pom.xml` (for Maven) or `build.gradle` (for Gradle).
Maven Dependency:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
```
Gradle Dependency:
```groovy
implementation 'org.springframework.boot:spring-boot-starter-web'
```
Step 2: Create the Main Application Class
Create the main class for the Spring Boot application.
```java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
```
Explanation:
@SpringBootApplication
: Indicates a configuration class that declares one or more@Bean
methods and also triggers auto-configuration and component scanning
Step 3: Create a REST Controller
Create a simple REST controller using the @RestController
annotation.
```java
package com.example.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, World!";
}
}
```
Explanation:
@RestController
: Indicates that the class is a REST controller.@RequestMapping("/api")
: Base URL for all endpoints in this controller.@GetMapping("/hello")
: Maps HTTP GET requests to thesayHello
method, which returns a string.
Step 4: Running the Application
Run the application from the main class (`DemoApplication`). When you navigate to `http://localhost:8080/api/hello` in your web browser, you should see the message: “Hello, World!”.
Conclusion RestController annotation
- @RestController: Combines `@Controller` and `@ResponseBody`, indicating that the class handles REST requests and the methods return data directly to the client.
- Example: Demonstrated how to use `@RestController` to create a simple REST API endpoint in a Spring Boot application.