Scrivio Interview library
ConceptFoundations5 min read · updated 12 November 2026

What is @RestControllerAdvice, and how do you limit it to certain controllers?

@RestControllerAdvice is @ControllerAdvice combined with @ResponseBody, so its @ExceptionHandler methods write their return values straight into the response body as JSON. By default it applies to every controller in the application. We limit it with its attributes basePackages, basePackageClasses, assignableTypes or annotations, and when several advices exist we order them with @Order, because the first advice with a matching handler wins.

Why this question is asked

Writing an @ExceptionHandler in every controller quickly leads to copies of the same code, and copies drift. A controller advice moves that code into one class that applies to many controllers. Interviewers ask about it because it is the standard way to build consistent error responses in Spring MVC, and the follow-ups, how to scope it and how several advices interact, are where real projects get into trouble. In this answer, we will recap what the annotation is made of, write a simple advice, see how to limit it to certain controllers, and look at ordering when there is more than one.

1A Quick Recap: @ControllerAdvice Plus @ResponseBody

@ControllerAdvice marks a class whose methods apply across many controllers. It can hold three kinds of methods: @ExceptionHandler methods for errors, @InitBinder methods that configure data binding, and @ModelAttribute methods that add attributes to the model. It is itself a @Component, so component scanning picks it up.

@ResponseBody tells Spring that a method's return value is the response body, converted by a message converter such as Jackson into JSON, rather than the name of a view to render. @RestControllerAdvice is simply both annotations together, exactly like @RestController is @Controller plus @ResponseBody.

Java
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@ControllerAdvice
@ResponseBody
public @interface RestControllerAdvice { ... } // simplified from the Spring source

So in a @RestControllerAdvice, every handler method behaves as if it had @ResponseBody, which is what we want in a REST API.

2A Simple Advice That Applies Everywhere

Without any attributes, the advice applies to all controllers in the application.

Java
@RestControllerAdvice
class ApiErrors {
@ExceptionHandler(NotFoundException.class)
ProblemDetail notFound(NotFoundException ex) {
return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
}
}
// GET /orders/42 -> 404 from OrderController via ApiErrors
// GET /products/7 -> 404 from ProductController via ApiErrors

Notice that a handler declared inside a controller still takes precedence. Spring checks the throwing controller's own @ExceptionHandler methods first and only then the advices, so a controller can override the global behaviour for itself.

3Limiting It to Certain Controllers

Often one application has two kinds of controllers, for example a public JSON API and an admin area that renders HTML pages, and they need different error responses. The annotation's attributes select which controllers an advice applies to.

Java
@RestControllerAdvice(basePackages = "com.example.shop.api") // controllers in this package and below
class PublicApiErrors { ... }
@RestControllerAdvice(basePackageClasses = AdminApi.class) // type-safe: the package of AdminApi
class AdminErrors { ... }
@RestControllerAdvice(assignableTypes = { OrderController.class, PaymentController.class })
class CheckoutErrors { ... } // these classes and their subclasses
@RestControllerAdvice(annotations = PublicApi.class) // controllers carrying @PublicApi
class AnnotatedErrors { ... }
Choosing a selector
AttributeMatchesGood for
basePackages / valuecontrollers in a package and its subpackagesa module laid out by package
basePackageClassesthe package of the given classthe same, safe under refactoring
assignableTypesgiven classes and their subtypesa few specific controllers
annotationscontrollers with a given annotationa marker like @PublicApi
All selectors are OR-ed together; with none, the advice applies to every controller.

Each attribute is a different selector. basePackages, also available as value, matches by package name, and basePackageClasses does the same but uses a class as a refactoring-safe marker for its package. assignableTypes matches the listed controller classes and anything that extends or implements them. annotations matches controllers that carry one of the given annotations, which works well with a custom marker annotation such as @PublicApi.

If we combine several selectors on one advice, a controller matches when it satisfies any of them; they are combined with OR, not AND. The checks are made at runtime, so the Spring documentation advises keeping selectors simple.

4Ordering When Several Advices Exist

When two advices can both handle an exception, the order decides. Spring sorts advice beans by @Order or the Ordered interface, lower values first, and goes through them one by one. The first advice that has any matching handler is used, even if a later advice has a handler for a more specific exception type.

Java
@RestControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
class OrderErrors {
@ExceptionHandler(OrderNotFoundException.class) ProblemDetail notFound(...) { ... }
}
@RestControllerAdvice
@Order(Ordered.LOWEST_PRECEDENCE)
class FallbackErrors {
@ExceptionHandler(Exception.class) ProblemDetail any(Exception ex) { ... } // catch-all
}
// OrderNotFoundException -> OrderErrors.notFound (checked first)
// IllegalStateException -> FallbackErrors.any

Without @Order, both advices have the lowest precedence, and their relative order depends on how the beans happened to be registered, which can change between builds. So whenever an application has more than one advice, and especially when one contains a catch-all handler for Exception, we give each one an explicit order and put the catch-all last.

5Follow-up questions

Does a scoped advice still handle errors from servlet filters?

No advice does. Controller advice is used by DispatcherServlet for exceptions raised while handling a request inside Spring MVC. Exceptions thrown in a filter happen before DispatcherServlet and go to the container's error page, /error in Spring Boot.

Can a @RestControllerAdvice hold @ModelAttribute or @InitBinder methods?

Yes, and they follow the same selectors. An @InitBinder method in an advice scoped to com.example.shop.api would, for example, register a custom property editor for every controller in that package. In REST APIs this is less common, but it is a tidy place for binder settings that many controllers share.

Should a library ship a @RestControllerAdvice?

It can, but it should give its advice an explicit low precedence and preferably register it through auto-configuration that a service can switch off. Otherwise its catch-all handlers can silently take over exceptions that the service meant to handle itself.

6Conclusion

In this answer, we saw that @RestControllerAdvice is @ControllerAdvice plus @ResponseBody, so its handlers return JSON bodies for exceptions from any controller. A controller's own handlers come first, and an advice applies to all controllers unless we limit it with basePackages, basePackageClasses, assignableTypes or annotations, which are combined with OR. When several advices exist, we give each an explicit @Order, since the first advice with a matching handler wins.

What to say in the interviewAbout 80 seconds aloud

Open with

@RestControllerAdvice is a composed annotation: @ControllerAdvice plus @ResponseBody, the same way @RestController is @Controller plus @ResponseBody. @ControllerAdvice makes a component whose @ExceptionHandler, @InitBinder and @ModelAttribute methods apply across controllers, and @ResponseBody means the handlers' return values, like a ProblemDetail or a record, are written as the JSON body instead of being treated as a view name.

Then, if they want more

By default it applies to every controller, although a handler inside a controller is checked first and can override it. To limit it I use its attributes: basePackages or value for a package, basePackageClasses for the same thing in a refactoring-safe way, assignableTypes for specific controller classes and their subclasses, or annotations for controllers carrying a marker annotation like @PublicApi.

If I set several, they're OR-ed. When there's more than one advice, order matters: Spring sorts them by @Order and uses the first advice that has any matching handler, even if a later one has a more specific match. So I give every advice an explicit order and put catch-all handlers for Exception in the lowest-precedence one.

One limit to remember is that advices only see exceptions from inside Spring MVC, not from servlet filters.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "What is @RestControllerAdvice, and how do you limit it to certain controllers?": https://scrivio-interview-library.netlify.app/spring-boot/error-handling/5d6bec1920/

More in Error handling