@RestController is a stereotype annotation that combines @ResponseBody and @Controller.
The annotation @RestController is meta annotated with @Controller and @ResponseBody, that means we don't have to explicitly annotate our handler methods with @ResponseBody, but we still have to use @RequestBody in our handler method parameters.
Example using @RestController
Create Backing Object
package com.logicbig.example;
import java.io.Serializable;
public class User implements Serializable {
private Long id;
private String name;
private String password;
private String emailAddress;
.............
}
Create Controller
package com.logicbig.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("users")
public class UserController {
@Autowired
private UserService userService;
@PostMapping(value = "register",
consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.CREATED)
public String handleJsonPostRequest(@RequestBody User user,
Model model) {
userService.saveUser(user);
return "User created with id: " + user.getId();
}
@GetMapping(
produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public List<User> handleAllUserRequest() {
return userService.getAllUsers();
}
}
Integration Test
package com.logicbig.example;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig;
import org.springframework.test.web.servlet.assertj.MockMvcTester;
import org.springframework.web.context.WebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
@SpringJUnitWebConfig(MyWebConfig.class)
public class ControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvcTester mockMvcTester;
@BeforeEach
public void setup() {
this.mockMvcTester = MockMvcTester.from(this.wac);
}
@Test
public void testUserController() {
assertThat(this.mockMvcTester.post().uri("/users/register")
.contentType(MediaType.APPLICATION_JSON)
.content(createUserInJson("joe",
"joe@example.com",
"abc"))
.exchange())
.hasStatus(org.springframework.http.HttpStatus.CREATED)
.bodyText().isEqualTo("User created with id: 1");
assertThat(this.mockMvcTester.post().uri("/users/register")
.contentType(MediaType.APPLICATION_JSON)
.content(createUserInJson("mike",
"mike@example.com",
"123"))
.exchange())
.hasStatus(org.springframework.http.HttpStatus.CREATED)
.bodyText().isEqualTo("User created with id: 2");
assertThat(this.mockMvcTester.get().uri("/users")
.accept(MediaType.APPLICATION_JSON)
.exchange())
.hasStatusOk()
.bodyJson()
.extractingPath("$[*].name").asArray().containsExactlyInAnyOrder("joe", "mike");
assertThat(this.mockMvcTester.get().uri("/users")
.accept(MediaType.APPLICATION_JSON)
.exchange())
.bodyJson()
.extractingPath("$[*].id").asArray().containsExactlyInAnyOrder(1, 2);
}
private static String createUserInJson(String name,
String email,
String password) {
return "{ \"name\": \"" + name + "\", " +
"\"emailAddress\":\"" + email + "\"," +
"\"password\":\"" + password + "\"}";
}
}
mvn clean test -Dtest="ControllerTest" Output$ mvn clean test -Dtest="ControllerTest" [INFO] Scanning for projects... [INFO] [INFO] ------------< com.logicbig.example:spring-rest-controller >------------- [INFO] Building spring-rest-controller 1.0-SNAPSHOT [INFO] from pom.xml [INFO] --------------------------------[ war ]--------------------------------- [INFO] [INFO] --- clean:3.2.0:clean (default-clean) @ spring-rest-controller --- [INFO] Deleting D:\example-projects\spring-mvc\spring-rest-controller\target [INFO] [INFO] --- resources:3.3.1:resources (default-resources) @ spring-rest-controller --- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory D:\example-projects\spring-mvc\spring-rest-controller\src\main\resources [INFO] [INFO] --- compiler:3.15.0:compile (default-compile) @ spring-rest-controller --- [INFO] Recompiling the module because of changed source code. [INFO] Compiling 6 source files with javac [debug target 25] to target\classes [INFO] [INFO] --- resources:3.3.1:testResources (default-testResources) @ spring-rest-controller --- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory D:\example-projects\spring-mvc\spring-rest-controller\src\test\resources [INFO] [INFO] --- compiler:3.15.0:testCompile (default-testCompile) @ spring-rest-controller --- [INFO] Recompiling the module because of changed dependency. [INFO] Compiling 2 source files with javac [debug target 25] to target\test-classes [INFO] [INFO] --- surefire:3.2.5:test (default-test) @ spring-rest-controller --- [INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider [WARNING] file.encoding cannot be set as system property, use <argLine>-Dfile.encoding=...</argLine> instead [INFO] [INFO] ------------------------------------------------------- [INFO] T E S T S [INFO] ------------------------------------------------------- [INFO] Running com.logicbig.example.ControllerTest [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.248 s -- in com.logicbig.example.ControllerTest [INFO] [INFO] Results: [INFO] [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 9.702 s [INFO] Finished at: 2026-07-26T18:17:26+08:00 [INFO] ------------------------------------------------------------------------
Example ProjectDependencies and Technologies Used: - spring-webmvc 7.0.6 (Spring Web MVC)
Version Compatibility: 4.0.0.RELEASE - 7.0.6 Version compatibilities of spring-webmvc with this example: Versions in green have been tested.
- spring-test 7.0.6 (Spring TestContext Framework)
- jakarta.servlet-api 6.1.0 (Jakarta Servlet API documentation)
- junit-jupiter-engine 6.0.3 (Module "junit-jupiter-engine" of JUnit)
- jackson-databind 2.21.1 (General data-binding functionality for Jackson: works on core streaming API)
- hamcrest 3.0 (Core API and libraries of hamcrest matcher framework)
- json-path 2.10.0 (A library to query and verify JSON)
- assertj-core 3.26.3 (Rich and fluent assertions for testing in Java)
- JDK 25
- Maven 3.9.11
|