Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure which controllers Spring @ControllerAdvice will be applied to?

I have two types of controllers in my spring application.

  • View controllers that forward to views to generate HTML
  • API controllers that return JSON directly from the controllers

Both the API and View controllers are part of the same spring dispatcher servlet. Spring 3.2 introduced the @ControllerAdvice annotation to allow for a global location to handle exception.

The documentation implies that @ControllerAdvice will be applied to every controller associated with a Dispatcher Servlet.

Is there a way to configure which controllers @ControllerAdvice will apply to?

For example in my scenario I want a @ControllerAdvice for my View Controllers and separate @ControllerAdvice for my API controllers.

like image 576
ams Avatar asked Jan 26 '13 23:01

ams


2 Answers

For people that will still find this question:

As from Spring 4 ControlerAdvice's can be limited to Controler's with the specified annotations. Take a look at:

http://blog.codeleak.pl/2013/11/controlleradvice-improvements-in-spring.html

(second half of this article) for more details.

like image 156
Adam from WALCZAK.IT Avatar answered Apr 27 '23 22:04

Adam from WALCZAK.IT


UPDATE

I am using spring 4. You can do one of 2 below options.

(1) You can add the packages you want. (Inside those packages you have controllers that you want to follow @ControllerAdvice).

Ex:

@ControllerAdvice(basePackages={"my.pkg.a", "my.pkg.b"})

(2) You can directly add the controller classes you want.

Ex:

@ControllerAdvice(basePackageClasses={MyControllerA.class, MyControllerB.class})
like image 36
Supun Wijerathne Avatar answered Apr 27 '23 23:04

Supun Wijerathne