Understanding @ControllerAdvice in Spring Boot

Spring Boot makes it easier to build web applications with useful features like automatic configuration and easy handling of requests. One of these helpful features is @ControllerAdvice. In this blog post, we will explain what @ControllerAdvice is, how it works, and how to use it in your Spring Boot applications.

What is @ControllerAdvice?

@ControllerAdvice is an annotation in Spring Boot that allows you to handle exceptions, add common data to the model, and apply other configurations across all controllers in your application. It works like a helper for managing your controllers without repeating code in each one.

In simple words, @ControllerAdvice helps you handle errors and manage data in a centralized way for all your controllers. It can be used to:

  • Handle exceptions globally across all controllers.
  • Add common data to the model that can be used by all controllers.
  • Set up global settings like input validation.

Let’s take a closer look at how to use @ControllerAdvice in your Spring Boot application.


Why Should You Use @ControllerAdvice?

  1. Handle Exceptions Globally Instead of handling exceptions in each controller, @ControllerAdvice allows you to handle them in one place. This makes your code cleaner and easier to manage.
  2. Reduce Code Duplication You can use @ControllerAdvice to manage cross-cutting concerns (like error handling and model setup) without repeating code in every controller.
  3. Return Meaningful Error Messages By using @ControllerAdvice, you can customize error messages or HTTP response codes for specific exceptions, which is useful for APIs.


How to Use @ControllerAdvice in Spring Boot

To use @ControllerAdvice, follow these steps:

  1. Create a @ControllerAdvice Class First, create a class and annotate it with @ControllerAdvice. This will be the class where you handle exceptions and set up global settings.
  2. Add Exception Handling Methods Inside the @ControllerAdvice class, you can use @ExceptionHandler to define methods that will handle exceptions for all controllers.
  3. Add Common Data with @ModelAttribute You can use @ModelAttribute to add data to the model that will be available in all controllers.


Example: Basic @ControllerAdvice Usage

Let’s say you want to handle a custom exception called ResourceNotFoundException globally and return a meaningful error message. Here’s how to do it.

Step 1: Define a Custom Exception

First, create a custom exception class.

public class ResourceNotFoundException extends RuntimeException {
    public ResourceNotFoundException(String message) {
        super(message);
    }
}        

Step 2: Create the @ControllerAdvice Class

Now, create a @ControllerAdvice class to handle this exception.

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;

@ControllerAdvice
public class GlobalExceptionHandler {

    // Handle ResourceNotFoundException globally
    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<String> handleResourceNotFoundException(ResourceNotFoundException ex) {
        return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
    }

    // Add common attribute to the model for all controllers
    @ModelAttribute
    public void addCommonAttributes(Model model) {
        model.addAttribute("appName", "My Spring Boot Application");
    }
}        

Step 3: Throw the Exception in a Controller

Now, create a controller where you will throw the ResourceNotFoundException when a resource is not found.

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @GetMapping("/resource/{id}")
    public String getResourceById(@PathVariable String id) {
        if ("123".equals(id)) {
            return "Resource found!";
        } else {
            throw new ResourceNotFoundException("Resource not found with id: " + id);
        }
    }
}        

How It Works:

  • When a user tries to access /resource/{id}, and the ID is not "123", the ResourceNotFoundException will be thrown.
  • The @ControllerAdvice class catches this exception and returns a custom error message with a 404 Not Found status.
  • The common attribute appName is automatically added to the model, which can be used in any controller.

Conclusion

@ControllerAdvice is a helpful feature in Spring Boot that allows you to handle exceptions, add common data, and configure global settings for your controllers. By using @ControllerAdvice, you can avoid repeating code, improve the readability of your application, and provide better error handling. Whether you are building a web application or an API, @ControllerAdvice will help make your code more efficient and easier to maintain.


Alexandre Pereira

Software Engineer MERN | React.JS | Nodejs | Javascript | Typescript | MongoDB | GCP | Python

5 天前

Very nice

回复
Erick Zanetti

Fullstack Engineer | Software Developer | React | Next.js | TypeScript | Node.js | JavaScript | AWS

6 天前

Very informative

回复
Alexandre Germano Souza de Andrade

Senior Software Engineer | Backend-Focused Fullstack Developer | .NET | C# | Angular | React.js | TypeScript | JavaScript | Azure | SQL Server

6 天前

Thanks for sharing JUNIOR NAKAMURA

回复
Eduardo Neto

Senior Fullstack Developer | Java, Angular & React Specialist | Oracle & AWS Certified

6 天前

Strong insight!!

回复
Daivid Sim?es

Senior QA Automation Engineer | SDET | Java | Selenium | Rest Assured | Robot Framework | Cypress | Appium

6 天前

Very informative

回复

要查看或添加评论,请登录

JUNIOR N.的更多文章

社区洞察