Reason remind fro @ControllerAdvice @ExceptiionHandler does not work

Configured following lines in web.xml for servlet:               

                <init-param>

<param-name>detectAllHandlerExceptionResolvers</param-name>

<param-value>false</param-value>

</init-param>

 

===================================explain for the exception handler ====================

The <mvc:annotation-driven/> element implicitly registers a ExceptionHandlerExceptionResolverbean. This class has a initExceptionHandlerAdviceCache() method which scans beans in the context to find those whose class type is annotated with @ControllerAdvice.

It does this by first calling ControllerAdviceBean.findAnnotatedBeans(ApplicationContext). Internally, this method uses ApplicationContext#getBeanDefinitionNames(). The javadoc of this method states

Does not consider any hierarchy this factory may participate

To clarify what this means. When you declare a ContextLoaderListener in your deployment descriptor, it loads what we call a root or application ApplicationContext and makes it available in the ServletContext. When you then declare a DispatcherServlet, it creates its own servlet ApplicationContext and uses any ApplicationContext it finds in the ServletContext attributes loaded by the ContextLoaderListener as a parent to that context. The hierarchy looks like so

Root ApplicationContext // loaded by the ContextLoaderListener
            |
Servlet ApplicationContext // loaded by the DispatcherServlet

Every ApplicationContext has access to beans in parent contexts, but not the other way around.

The method above chooses not to use the beans in parent contexts and so only has access to beans in the current ApplicationContext (BeanFactory really).

As such, if your

<context:component-scan .../>

is declared in a root ApplicationContext as I'll assume from the name app-config, but the

<mvc:annotation-driven />

is declared in the servlet ApplicationContext, again assuming from mvc-config, then the ExceptionHandlerExceptionResolver looking for @ControllerAdvice beans will not find any. It is looking for beans in the servlet context but they aren't there, they are in the root context.

你可能感兴趣的:(Reason remind fro @ControllerAdvice @ExceptiionHandler does not work)