Introduced ControllerAdvice annotation

Classes with this annotation can contain @ExceptionHandler,
@InitBinder, and @ModelAttribute methods that apply to all controllers.
The new annotation is also a component annotation allowing
implementations to be discovered through component scanning.

Issue: SPR-9112
This commit is contained in:
Rossen Stoyanchev
2012-07-26 13:37:49 -04:00
parent f1105812af
commit e65b930e7a
11 changed files with 440 additions and 239 deletions

View File

@@ -26,16 +26,16 @@ import org.springframework.web.servlet.ModelAndView;
* Abstract base class for
* {@link org.springframework.web.servlet.HandlerExceptionResolver HandlerExceptionResolver}
* implementations that support handling exceptions from handlers of type {@link HandlerMethod}.
*
*
* @author Rossen Stoyanchev
* @since 3.1
*/
public abstract class AbstractHandlerMethodExceptionResolver extends AbstractHandlerExceptionResolver {
/**
* Checks if the handler is a {@link HandlerMethod} instance and performs the check against the bean
* instance it contains. If the provided handler is not an instance of {@link HandlerMethod},
* {@code false} is returned instead.
* Checks if the handler is a {@link HandlerMethod} and then delegates to the
* base class implementation of {@link #shouldApplyTo(HttpServletRequest, Object)}
* passing the bean of the {@code HandlerMethod}. Otherwise returns {@code false}.
*/
@Override
protected boolean shouldApplyTo(HttpServletRequest request, Object handler) {
@@ -51,7 +51,7 @@ public abstract class AbstractHandlerMethodExceptionResolver extends AbstractHan
return false;
}
}
@Override
protected final ModelAndView doResolveException(
HttpServletRequest request, HttpServletResponse response,
@@ -59,7 +59,7 @@ public abstract class AbstractHandlerMethodExceptionResolver extends AbstractHan
return doResolveHandlerMethodException(request, response, (HandlerMethod) handler, ex);
}
/**
* Actually resolve the given exception that got thrown during on handler execution,
* returning a ModelAndView that represents a specific error page if appropriate.

View File

@@ -19,7 +19,6 @@ package org.springframework.web.servlet.mvc.method.annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -34,16 +33,15 @@ import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.OrderComparator;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.xml.SourceHttpMessageConverter;
import org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ExceptionResolver;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.support.ControllerAdviceBean;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.method.annotation.ExceptionHandlerMethodResolver;
@@ -82,11 +80,11 @@ public class ExceptionHandlerExceptionResolver extends AbstractHandlerMethodExce
private ContentNegotiationManager contentNegotiationManager = new ContentNegotiationManager();
private final Map<Class<?>, ExceptionHandlerMethodResolver> exceptionHandlersByType =
private final Map<Class<?>, ExceptionHandlerMethodResolver> exceptionHandlerCache =
new ConcurrentHashMap<Class<?>, ExceptionHandlerMethodResolver>();
private final Map<Object, ExceptionHandlerMethodResolver> globalExceptionHandlers =
new LinkedHashMap<Object, ExceptionHandlerMethodResolver>();
private final Map<ControllerAdviceBean, ExceptionHandlerMethodResolver> exceptionHandlerAdviceCache =
new LinkedHashMap<ControllerAdviceBean, ExceptionHandlerMethodResolver>();
private HandlerMethodArgumentResolverComposite argumentResolvers;
@@ -208,22 +206,14 @@ public class ExceptionHandlerExceptionResolver extends AbstractHandlerMethodExce
this.contentNegotiationManager = contentNegotiationManager;
}
/**
* Provide instances of objects with {@link ExceptionHandler @ExceptionHandler}
* methods to apply globally, i.e. regardless of the selected controller.
* <p>{@code @ExceptionHandler} methods in the controller are always looked
* up before {@code @ExceptionHandler} methods in global handlers.
*/
public void setGlobalExceptionHandlers(Object... handlers) {
for (Object handler : handlers) {
this.globalExceptionHandlers.put(handler, new ExceptionHandlerMethodResolver(handler.getClass()));
}
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public ApplicationContext getApplicationContext() {
return this.applicationContext;
}
public void afterPropertiesSet() {
if (this.argumentResolvers == null) {
List<HandlerMethodArgumentResolver> resolvers = getDefaultArgumentResolvers();
@@ -233,7 +223,7 @@ public class ExceptionHandlerExceptionResolver extends AbstractHandlerMethodExce
List<HandlerMethodReturnValueHandler> handlers = getDefaultReturnValueHandlers();
this.returnValueHandlers = new HandlerMethodReturnValueHandlerComposite().addHandlers(handlers);
}
initGlobalExceptionHandlers();
initExceptionHandlerAdviceCache();
}
/**
@@ -287,39 +277,28 @@ public class ExceptionHandlerExceptionResolver extends AbstractHandlerMethodExce
return handlers;
}
private void initGlobalExceptionHandlers() {
if (this.applicationContext == null) {
logger.warn("Can't detect @ExceptionResolver components if the ApplicationContext property is not set");
private void initExceptionHandlerAdviceCache() {
if (getApplicationContext() == null) {
return;
}
else {
String[] beanNames = this.applicationContext.getBeanNamesForType(Object.class);
for (String name : beanNames) {
Class<?> type = this.applicationContext.getType(name);
if (AnnotationUtils.findAnnotation(type , ExceptionResolver.class) != null) {
Object bean = this.applicationContext.getBean(name);
this.globalExceptionHandlers.put(bean, new ExceptionHandlerMethodResolver(bean.getClass()));
}
}
if (logger.isDebugEnabled()) {
logger.debug("Looking for exception mappings: " + getApplicationContext());
}
if (this.globalExceptionHandlers.size() > 0) {
sortGlobalExceptionHandlers();
}
}
private void sortGlobalExceptionHandlers() {
Map<Object, ExceptionHandlerMethodResolver> handlersCopy =
new HashMap<Object, ExceptionHandlerMethodResolver>(this.globalExceptionHandlers);
List<Object> handlers = new ArrayList<Object>(handlersCopy.keySet());
Collections.sort(handlers, new AnnotationAwareOrderComparator());
this.globalExceptionHandlers.clear();
for (Object handler : handlers) {
this.globalExceptionHandlers.put(handler, handlersCopy.get(handler));
List<ControllerAdviceBean> beans = ControllerAdviceBean.findBeans(getApplicationContext());
Collections.sort(beans, new OrderComparator());
for (ControllerAdviceBean bean : beans) {
ExceptionHandlerMethodResolver resolver = new ExceptionHandlerMethodResolver(bean.getBeanType());
if (resolver.hasExceptionMappings()) {
this.exceptionHandlerAdviceCache.put(bean, resolver);
logger.info("Detected @ExceptionHandler methods in " + bean);
}
}
}
/**
* Find an @{@link ExceptionHandler} method and invoke it to handle the
* raised exception.
* Find an {@code @ExceptionHandler} method and invoke it to handle the raised exception.
*/
@Override
protected ModelAndView doResolveHandlerMethodException(HttpServletRequest request,
@@ -361,9 +340,11 @@ public class ExceptionHandlerExceptionResolver extends AbstractHandlerMethodExce
}
/**
* Find the @{@link ExceptionHandler} method for the given exception.
* The default implementation searches @{@link ExceptionHandler} methods
* in the class hierarchy of the method that raised the exception.
* Find an {@code @ExceptionHandler} method for the given exception. The default
* implementation searches methods in the class hierarchy of the controller first
* and if not found, it continues searching for additional {@code @ExceptionHandler}
* methods assuming some {@linkplain ControllerAdvice @ControllerAdvice}
* Spring-managed beans were detected.
* @param handlerMethod the method where the exception was raised, possibly {@code null}
* @param exception the raised exception
* @return a method to handle the exception, or {@code null}
@@ -371,27 +352,20 @@ public class ExceptionHandlerExceptionResolver extends AbstractHandlerMethodExce
protected ServletInvocableHandlerMethod getExceptionHandlerMethod(HandlerMethod handlerMethod, Exception exception) {
if (handlerMethod != null) {
Class<?> handlerType = handlerMethod.getBeanType();
ExceptionHandlerMethodResolver resolver = this.exceptionHandlersByType.get(handlerType);
ExceptionHandlerMethodResolver resolver = this.exceptionHandlerCache.get(handlerType);
if (resolver == null) {
resolver = new ExceptionHandlerMethodResolver(handlerType);
this.exceptionHandlersByType.put(handlerType, resolver);
this.exceptionHandlerCache.put(handlerType, resolver);
}
Method method = resolver.resolveMethod(exception);
if (method != null) {
return new ServletInvocableHandlerMethod(handlerMethod.getBean(), method);
}
}
return getGlobalExceptionHandlerMethod(exception);
}
/**
* Return a global {@code @ExceptionHandler} method for the given exception or {@code null}.
*/
private ServletInvocableHandlerMethod getGlobalExceptionHandlerMethod(Exception exception) {
for (Entry<Object, ExceptionHandlerMethodResolver> entry : this.globalExceptionHandlers.entrySet()) {
for (Entry<ControllerAdviceBean, ExceptionHandlerMethodResolver> entry : this.exceptionHandlerAdviceCache.entrySet()) {
Method method = entry.getValue().resolveMethod(exception);
if (method != null) {
return new ServletInvocableHandlerMethod(entry.getKey(), method);
return new ServletInvocableHandlerMethod(entry.getKey().resolveBean(), method);
}
}
return null;

View File

@@ -19,8 +19,11 @@ package org.springframework.web.servlet.mvc.method.annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@@ -36,6 +39,7 @@ import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.OrderComparator;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.task.AsyncTaskExecutor;
@@ -53,6 +57,7 @@ import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.support.ControllerAdviceBean;
import org.springframework.web.bind.support.DefaultDataBinderFactory;
import org.springframework.web.bind.support.DefaultSessionAttributeStore;
import org.springframework.web.bind.support.SessionAttributeStore;
@@ -62,9 +67,9 @@ import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.context.request.async.AsyncWebRequest;
import org.springframework.web.context.request.async.AsyncWebUtils;
import org.springframework.web.context.request.async.NoSupportAsyncWebRequest;
import org.springframework.web.context.request.async.WebAsyncManager;
import org.springframework.web.context.request.async.AsyncWebUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.method.HandlerMethodSelector;
import org.springframework.web.method.annotation.ErrorsMethodArgumentResolver;
@@ -142,9 +147,15 @@ public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter i
private HandlerMethodReturnValueHandlerComposite returnValueHandlers;
private final Map<Class<?>, Set<Method>> dataBinderFactoryCache = new ConcurrentHashMap<Class<?>, Set<Method>>();
private final Map<Class<?>, Set<Method>> initBinderCache = new ConcurrentHashMap<Class<?>, Set<Method>>();
private final Map<Class<?>, Set<Method>> modelFactoryCache = new ConcurrentHashMap<Class<?>, Set<Method>>();
private final Map<ControllerAdviceBean, Set<Method>> initBinderAdviceCache =
new LinkedHashMap<ControllerAdviceBean, Set<Method>>();
private final Map<Class<?>, Set<Method>> modelAttributeCache = new ConcurrentHashMap<Class<?>, Set<Method>>();
private final Map<ControllerAdviceBean, Set<Method>> modelAttributeAdviceCache =
new LinkedHashMap<ControllerAdviceBean, Set<Method>>();
private AsyncTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor("MvcAsync");
@@ -152,6 +163,7 @@ public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter i
private ContentNegotiationManager contentNegotiationManager = new ContentNegotiationManager();
/**
* Default constructor.
*/
@@ -454,6 +466,7 @@ public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter i
List<HandlerMethodReturnValueHandler> handlers = getDefaultReturnValueHandlers();
this.returnValueHandlers = new HandlerMethodReturnValueHandlerComposite().addHandlers(handlers);
}
initControllerAdviceCache();
}
/**
@@ -565,6 +578,31 @@ public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter i
return handlers;
}
private void initControllerAdviceCache() {
if (getApplicationContext() == null) {
return;
}
if (logger.isDebugEnabled()) {
logger.debug("Looking for controller advice: " + getApplicationContext());
}
List<ControllerAdviceBean> beans = ControllerAdviceBean.findBeans(getApplicationContext());
Collections.sort(beans, new OrderComparator());
for (ControllerAdviceBean bean : beans) {
Set<Method> attrMethods = HandlerMethodSelector.selectMethods(bean.getBeanType(), MODEL_ATTRIBUTE_METHODS);
if (!attrMethods.isEmpty()) {
this.modelAttributeAdviceCache.put(bean, attrMethods);
logger.info("Detected @ModelAttribute methods in " + bean);
}
Set<Method> binderMethods = HandlerMethodSelector.selectMethods(bean.getBeanType(), INIT_BINDER_METHODS);
if (!binderMethods.isEmpty()) {
this.initBinderAdviceCache.put(bean, binderMethods);
logger.info("Detected @InitBinder methods in " + bean);
}
}
}
/**
* Always return {@code true} since any method argument and return value
* type will be processed in some way. A method argument not recognized
@@ -694,38 +732,60 @@ public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter i
private ModelFactory getModelFactory(HandlerMethod handlerMethod, WebDataBinderFactory binderFactory) {
SessionAttributesHandler sessionAttrHandler = getSessionAttributesHandler(handlerMethod);
Class<?> handlerType = handlerMethod.getBeanType();
Set<Method> methods = this.modelFactoryCache.get(handlerType);
Set<Method> methods = this.modelAttributeCache.get(handlerType);
if (methods == null) {
methods = HandlerMethodSelector.selectMethods(handlerType, MODEL_ATTRIBUTE_METHODS);
this.modelFactoryCache.put(handlerType, methods);
this.modelAttributeCache.put(handlerType, methods);
}
List<InvocableHandlerMethod> attrMethods = new ArrayList<InvocableHandlerMethod>();
for (Method method : methods) {
InvocableHandlerMethod attrMethod = new InvocableHandlerMethod(handlerMethod.getBean(), method);
attrMethod.setHandlerMethodArgumentResolvers(this.argumentResolvers);
attrMethod.setParameterNameDiscoverer(this.parameterNameDiscoverer);
attrMethod.setDataBinderFactory(binderFactory);
attrMethods.add(attrMethod);
Object bean = handlerMethod.getBean();
attrMethods.add(createModelAttributeMethod(binderFactory, bean, method));
}
for (Entry<ControllerAdviceBean, Set<Method>> entry : this.modelAttributeAdviceCache.entrySet()) {
Object bean = entry.getKey().resolveBean();
for (Method method : entry.getValue()) {
attrMethods.add(createModelAttributeMethod(binderFactory, bean, method));
}
}
return new ModelFactory(attrMethods, binderFactory, sessionAttrHandler);
}
private InvocableHandlerMethod createModelAttributeMethod(WebDataBinderFactory factory, Object bean, Method method) {
InvocableHandlerMethod attrMethod = new InvocableHandlerMethod(bean, method);
attrMethod.setHandlerMethodArgumentResolvers(this.argumentResolvers);
attrMethod.setParameterNameDiscoverer(this.parameterNameDiscoverer);
attrMethod.setDataBinderFactory(factory);
return attrMethod;
}
private WebDataBinderFactory getDataBinderFactory(HandlerMethod handlerMethod) throws Exception {
Class<?> handlerType = handlerMethod.getBeanType();
Set<Method> methods = this.dataBinderFactoryCache.get(handlerType);
Set<Method> methods = this.initBinderCache.get(handlerType);
if (methods == null) {
methods = HandlerMethodSelector.selectMethods(handlerType, INIT_BINDER_METHODS);
this.dataBinderFactoryCache.put(handlerType, methods);
this.initBinderCache.put(handlerType, methods);
}
List<InvocableHandlerMethod> binderMethods = new ArrayList<InvocableHandlerMethod>();
List<InvocableHandlerMethod> initBinderMethods = new ArrayList<InvocableHandlerMethod>();
for (Method method : methods) {
InvocableHandlerMethod binderMethod = new InvocableHandlerMethod(handlerMethod.getBean(), method);
binderMethod.setHandlerMethodArgumentResolvers(this.initBinderArgumentResolvers);
binderMethod.setDataBinderFactory(new DefaultDataBinderFactory(this.webBindingInitializer));
binderMethod.setParameterNameDiscoverer(this.parameterNameDiscoverer);
binderMethods.add(binderMethod);
Object bean = handlerMethod.getBean();
initBinderMethods.add(createInitBinderMethod(bean, method));
}
return createDataBinderFactory(binderMethods);
for (Entry<ControllerAdviceBean, Set<Method>> entry : this.initBinderAdviceCache .entrySet()) {
Object bean = entry.getKey().resolveBean();
for (Method method : entry.getValue()) {
initBinderMethods.add(createInitBinderMethod(bean, method));
}
}
return createDataBinderFactory(initBinderMethods);
}
private InvocableHandlerMethod createInitBinderMethod(Object bean, Method method) {
InvocableHandlerMethod binderMethod = new InvocableHandlerMethod(bean, method);
binderMethod.setHandlerMethodArgumentResolvers(this.initBinderArgumentResolvers);
binderMethod.setDataBinderFactory(new DefaultDataBinderFactory(this.webBindingInitializer));
binderMethod.setParameterNameDiscoverer(this.parameterNameDiscoverer);
return binderMethod;
}
/**
@@ -738,6 +798,7 @@ public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter i
*/
protected ServletRequestDataBinderFactory createDataBinderFactory(List<InvocableHandlerMethod> binderMethods)
throws Exception {
return new ServletRequestDataBinderFactory(binderMethods, getWebBindingInitializer());
}