0
0
SpringbootConceptBeginner · 3 min read

@ControllerAdvice in Spring: What It Is and How It Works

@ControllerAdvice is a Spring annotation that allows you to handle exceptions and share common logic across multiple controllers globally. It acts like a centralized place to manage error handling, data binding, and model attributes for all controllers in your application.
⚙️

How It Works

Imagine you have many controllers in your Spring app, each handling different web requests. Instead of writing the same error handling or data setup code in each controller, @ControllerAdvice lets you write that code once and apply it everywhere.

It works like a helper that watches all controllers. When an exception happens or when you want to add common data to all views, the methods inside a class annotated with @ControllerAdvice get called automatically. This keeps your code clean and consistent.

💻

Example

This example shows a simple @ControllerAdvice that handles exceptions thrown by any controller and returns a friendly error message.

java
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.http.ResponseEntity;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleAllExceptions(Exception ex) {
        return ResponseEntity.status(500).body("Oops! Something went wrong: " + ex.getMessage());
    }
}
Output
If any controller throws an exception, the user sees: "Oops! Something went wrong: [error message]"
🎯

When to Use

Use @ControllerAdvice when you want to:

  • Handle exceptions globally instead of repeating code in each controller.
  • Add common data to all models, like user info or site settings.
  • Apply global data binding or validation rules.

For example, if your app has many pages and you want to show the logged-in user's name everywhere, @ControllerAdvice can add that data once for all controllers.

Key Points

  • @ControllerAdvice centralizes exception handling and common controller logic.
  • It applies to all controllers automatically.
  • Use @ExceptionHandler methods inside it to catch exceptions.
  • Can also add attributes to models globally with @ModelAttribute.
  • Keeps your controllers clean and your app consistent.

Key Takeaways

@ControllerAdvice centralizes error handling and shared logic for all controllers.
It helps avoid repeating code by applying common behavior globally.
Use @ExceptionHandler inside it to catch and respond to exceptions.
You can also add common data to all views with @ModelAttribute methods.
It keeps your Spring MVC app organized and easier to maintain.