Spring Boot @ResponseStatus Annotation

In this short article, we will learn how to use Spring Boot @ResponseStatus annotation in a Spring boot application. We create a Spring Boot RESTful application to demonstrate the annotation.

@ResponseStatus

@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 ResourceNotFoundException extends RuntimeException {
}

Spring Boot @ResponseStatus Annotation Example

In the following application, we demonstrate the usage of the @ResponseStatus annotation. The application simulates a form for retrieving user by their Id. Trying to find the user a by id, if the User is not found then we will throw ResourceNotFoundException.

Development Steps

  1. Create a Spring Boot Application
  2. Project Structure
  3. Pom Dependencies
  4. Java Bean - User.java
  5. Define Custom Exception
  6. Create REST Controller - UserController.java
  7. Run Application - Application.java
  8. Testing from Postman Client

1. Create a Spring Boot Application

There are many ways to create a Spring Boot application. You can refer below articles to create a Spring Boot application.
Refer project structure or packaging structure in the next step.

2. Project Structure

This is the project structure of the Spring Boot application that we are going to create - 

3. Pom Dependencies

This is the Maven build file. The spring-boot-starter-web is a starter for building web applications using Spring MVC. It uses Tomcat as the default embedded container.
<?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 http://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>2.0.5.RELEASE</version>
        <relativePath />
        <!-- lookup parent from repository -->
    </parent>
    <groupId>net.javaguides.springboot</groupId>
    <artifactId>springboot-annotations-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-annotations-demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</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>

4. Java Bean - User.java

Let's create a representation class which we use to bind to method parameters to request body:
package net.javaguides.springboot;

public class User {

    private Integer id;
    private String name;

    public User() {}

    public User(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

5. Define Custom Exception - ResourceNotFoundException.java

We have a custom ResourceNotFoundException. It is decorated with the @ResponseStatus annotation. The value is set to HttpStatus.NOT_FOUND.
package net.javaguides.springboot;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {

    private static final long serialVersionUID = 1 L;

    private String message;

    public ResourceNotFoundException(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

6. Create REST Controller - UserController.java

Let's create a simple UserController with users rest API which returns a User by Id, if the User is not found then we will throw ResourceNotFoundException.
package net.javaguides.springboot;

import java.util.HashMap;
import java.util.Map;

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.RestController;

@RestController
public class UserController {

    @GetMapping("/users/{id}")
    public ResponseEntity < User > getUser(
        @PathVariable(value = "id") Integer userId) throws ResourceNotFoundException {
        Map < Integer, User > map = new HashMap < > ();
        map.put(1, new User(1, "Ramesh"));
        map.put(2, new User(2, "Tony"));
        map.put(3, new User(3, "Tom"));

        if (!map.containsKey(userId)) {
            throw new ResourceNotFoundException("Resource not found for " + userId);
        }
        return ResponseEntity.ok(map.get(userId));
    }
}

7. 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 Eclipse IDE by right click - Run As - Java Application.
Or you can use the below maven command to run:
mvn spring-boot:run

8. Testing from Postman Rest Client



Comments