Spring @ResponseStatus Annotation Example
In this section we will learn about @ResponseStatus Annotation.
The @ResponseStatus marks a method or exception class with the status code and reason message that should be returned. The status code is applied to the HTTP response when the handler method is invoked, or whenever the specified exception is thrown. It overrides status information set by other means, like ResponseEntity or redirect.
Here is a sample code snippet:
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class UserNotFoundException extends RuntimeException {
}
The following example creates a Spring Boot web application which uses @ResponseStatus annotation.
Project Directory
Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.knf.dev.demo</groupId>
<artifactId>spring-responsestatus-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-responsestatus-example</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties
server.error.include-message=always
Define Custom Exception - UserNotFoundException.java
package com.knf.dev.demo.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class UserNotFoundException extends RuntimeException {
private static final long serialVersionUID = 1L;
private String message;
public UserNotFoundException(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
User.java
package com.knf.dev.demo.model;
public class User {
private Long id;
private String name;
public User(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
UserController.java
package com.knf.dev.demo.controller;
import com.knf.dev.demo.exception.UserNotFoundException;
import com.knf.dev.demo.model.User;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/api/v1")
public class UserController {
@GetMapping("/users/{id}")
public ResponseEntity<User> getUser(
@PathVariable(value = "id") Integer userId)
throws UserNotFoundException {
Map< Integer, User > map = new HashMap< >();
map.put(1, new User(1l, "Sibin"));
map.put(2, new User(2l, "Jerry"));
map.put(3, new User(3l, "Michael"));
if (!map.containsKey(userId)) {
throw new UserNotFoundException
("User not found for " + userId);
}
return ResponseEntity.ok(map.get(userId));
}
}
Run Application - Application.java
Application is the entry point that sets up the Spring Boot application. The @SpringBootApplication annotation enables auto-configuration and component scanning.
Let's run this Spring boot application from either IntelliJ IDEA IDE by right click - Run 'Application.main()'
Or you can use the below maven command to run:
mvn spring-boot:run
Try to send a GET request to the /users/8
endpoint using Postman.
More related topics,