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 Overview

In Spring Boot, the @ResponseStatus annotation is used to set custom HTTP status codes for controller methods or exception handlers. It allows you to specify an HTTP status without using ResponseEntity.

Key Features of @ResponseStatus:
 ✔ Sets custom HTTP response status codes.
 ✔ Works with exception handling.
 ✔ Eliminates the need for ResponseEntity.
 ✔ Supports custom error messages for better API responses.

1️⃣ Basic Example: Setting a Custom Response Status

📌 Example: Returning HTTP 201 Created for a New User

@RestController
@RequestMapping("/api/users")
public class UserController {

@PostMapping
@ResponseStatus(HttpStatus.CREATED) // Returns HTTP 201 Created
public String createUser(@RequestBody User user) {
return "User created successfully!";
}
}

2️⃣ Using @ResponseStatus for Exception Handling

Instead of manually returning a ResponseEntity, you can throw exceptions with @ResponseStatus to indicate errors.

📌 Example: Custom Exception with @ResponseStatus

@ResponseStatus(HttpStatus.NOT_FOUND) // Returns HTTP 404 Not Found
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message) {
super(message);
}
}

📌 Throwing the Exception in a Controller

@RestController
@RequestMapping("/api/users")
public class UserController {

private final Map<Integer, String> users = Map.of(1, "Ramesh", 2, "Suresh");

@GetMapping("/{id}")
public String getUserById(@PathVariable int id) {
if (!users.containsKey(id)) {
throw new UserNotFoundException("User not found with ID: " + id);
}
return users.get(id);
}
}

Spring Boot @ResponseStatus Annotation Complete 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 to the below articles to create a Spring Boot application.
Refer to the 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.
    <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>

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

8. Testing from Postman Rest Client



Using @ResponseStatus for Different HTTP Status Codes

@ResponseStatus vs ResponseEntity


📌 Example: Using ResponseEntity Instead of @ResponseStatus

@GetMapping("/{id}")
public ResponseEntity<String> getUserById(@PathVariable int id) {
if (!users.containsKey(id)) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body("User not found with ID: " + id);
}
return ResponseEntity.ok(users.get(id));
}

Use ResponseEntity when you need dynamic responses, otherwise @ResponseStatus is sufficient.


Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare