Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring 3.2 @ControllerAdvice Not Working

Tags:

I am having trouble getting @ControllerAdvice to work. I updated my namespace location, which were 3.1 in my xml files. I moved the class with the controller to the same package as the controller. I am using 3.2.0 release jars. If I put the @ExceptionHandler annotation in the controller code, it works, but not in a separate class with the @ControllerAdvice. When the @ControllerAdvice class fails, I get my uncaught exception handler view. Anyone have ideas on how to trouble shoot this one?

like image 526
Joe Avatar asked Aug 21 '13 00:08

Joe


2 Answers

If you use classpath scanning, probably you have to add new include filter to your <context:component-scan> element:

<context:include-filter type="annotation"      expression="org.springframework.web.bind.annotation.ControllerAdvice" /> 

Default scanning does not lookup this annotation, following spring-context-3.2.xsd for component-scan:

"Scans the classpath for annotated components that will be auto-registered as Spring beans. By default, the Spring-provided @Component, @Repository, @Service, and @Controller stereotypes will be detected."

like image 192
tunguski Avatar answered Oct 08 '22 18:10

tunguski


For this problem, The first thing is confirming your config,

  1. You need make sure that the @ControllerAdvice Class under your component-scan base package.
  2. Make suer you use <mvc:annotation-driven/> in your spring-servlet.xml. or have @EnableWebMvc in your @ControllerAdvice Class

When you have the config right, the ControllerAdvice should already work, Now you said You got your uncaught exception handler view. I guess you got that in your InegrationTest, And you used mockMvc to test that, If so, you need put @WebAppConfiguration and build mokcMvc as follow:

 @Autowired private WebApplicationContext wac;  mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); 

Using standaloneSetup(controller) will not work because lack of WebApplicationContext.

like image 43
xianlinbox Avatar answered Oct 08 '22 18:10

xianlinbox