@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.
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()); } }
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
@ExceptionHandlermethods 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.@ExceptionHandler inside it to catch and respond to exceptions.@ModelAttribute methods.