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());
}

View File

@@ -33,14 +33,13 @@ import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ExceptionResolver;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.method.annotation.ModelMethodProcessor;
@@ -164,7 +163,7 @@ public class ExceptionHandlerExceptionResolverTests {
}
@Test
public void resolveExceptionResponseWriter() throws UnsupportedEncodingException, NoSuchMethodException {
public void resolveExceptionResponseWriter() throws Exception {
IllegalArgumentException ex = new IllegalArgumentException();
HandlerMethod handlerMethod = new HandlerMethod(new ResponseWriterController(), "handle");
this.resolver.afterPropertiesSet();
@@ -176,28 +175,24 @@ public class ExceptionHandlerExceptionResolverTests {
}
@Test
public void resolveExceptionGlobalHandler() throws UnsupportedEncodingException, NoSuchMethodException {
public void resolveExceptionGlobalHandler() throws Exception {
AnnotationConfigApplicationContext cxt = new AnnotationConfigApplicationContext(MyConfig.class);
this.resolver.setApplicationContext(cxt);
this.resolver.setGlobalExceptionHandlers(new GlobalExceptionHandler());
this.resolver.afterPropertiesSet();
IllegalStateException ex = new IllegalStateException();
IllegalAccessException ex = new IllegalAccessException();
HandlerMethod handlerMethod = new HandlerMethod(new ResponseBodyController(), "handle");
ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex);
assertNotNull("Exception was not handled", mav);
assertTrue(mav.isEmpty());
assertEquals("IllegalStateException", this.response.getContentAsString());
assertEquals("AnotherTestExceptionResolver: IllegalAccessException", this.response.getContentAsString());
}
@Test
public void resolveExceptionGlobalHandlerOrdered() throws UnsupportedEncodingException, NoSuchMethodException {
public void resolveExceptionGlobalHandlerOrdered() throws Exception {
AnnotationConfigApplicationContext cxt = new AnnotationConfigApplicationContext(MyConfig.class);
this.resolver.setApplicationContext(cxt);
GlobalExceptionHandler globalHandler = new GlobalExceptionHandler();
globalHandler.setOrder(2);
this.resolver.setGlobalExceptionHandlers(globalHandler);
this.resolver.afterPropertiesSet();
IllegalStateException ex = new IllegalStateException();
@@ -206,7 +201,7 @@ public class ExceptionHandlerExceptionResolverTests {
assertNotNull("Exception was not handled", mav);
assertTrue(mav.isEmpty());
assertEquals("@ExceptionResolver: IllegalStateException", this.response.getContentAsString());
assertEquals("TestExceptionResolver: IllegalStateException", this.response.getContentAsString());
}
@@ -259,41 +254,37 @@ public class ExceptionHandlerExceptionResolverTests {
}
}
static class GlobalExceptionHandler implements Ordered {
private int order;
public int getOrder() {
return order;
}
public void setOrder(int order) {
this.order = order;
}
@ControllerAdvice
@Order(1)
static class TestExceptionResolver {
@ExceptionHandler
@ResponseBody
public String handleException(IllegalStateException ex) {
return ClassUtils.getShortName(ex.getClass());
return "TestExceptionResolver: " + ClassUtils.getShortName(ex.getClass());
}
}
@ExceptionResolver
@Order(1)
static class AnnotatedExceptionResolver {
@ControllerAdvice
@Order(2)
static class AnotherTestExceptionResolver {
@ExceptionHandler
@ExceptionHandler({IllegalStateException.class, IllegalAccessException.class})
@ResponseBody
public String handleException(IllegalStateException ex) {
return "@ExceptionResolver: " + ClassUtils.getShortName(ex.getClass());
public String handleException(Exception ex) {
return "AnotherTestExceptionResolver: " + ClassUtils.getShortName(ex.getClass());
}
}
@Configuration
static class MyConfig {
@Bean public AnnotatedExceptionResolver exceptionResolver() {
return new AnnotatedExceptionResolver();
@Bean public TestExceptionResolver testExceptionResolver() {
return new TestExceptionResolver();
}
@Bean public AnotherTestExceptionResolver anotherTestExceptionResolver() {
return new AnotherTestExceptionResolver();
}
}

View File

@@ -25,12 +25,10 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import org.aopalliance.aop.Advice;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.springframework.aop.Pointcut;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.aop.interceptor.SimpleTraceInterceptor;
import org.springframework.aop.support.DefaultPointcutAdvisor;
@@ -106,7 +104,7 @@ public class HandlerMethodAnnotationDetectionTests {
DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator();
autoProxyCreator.setBeanFactory(context.getBeanFactory());
context.getBeanFactory().addBeanPostProcessor(autoProxyCreator);
context.registerBeanDefinition("controllerAdvice", new RootBeanDefinition(ControllerAdvice.class));
context.registerBeanDefinition("controllerAdvice", new RootBeanDefinition(ControllerAdvisor.class));
}
context.refresh();
@@ -405,9 +403,10 @@ public class HandlerMethodAnnotationDetectionTests {
}
static class ControllerAdvice extends DefaultPointcutAdvisor {
@SuppressWarnings("serial")
static class ControllerAdvisor extends DefaultPointcutAdvisor {
public ControllerAdvice() {
public ControllerAdvisor() {
super(getControllerPointcut(), new SimpleTraceInterceptor());
}

View File

@@ -28,8 +28,10 @@ import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.support.GenericWebApplicationContext;
import org.springframework.web.context.support.StaticWebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.method.annotation.ModelMethodProcessor;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
@@ -51,31 +53,35 @@ import org.springframework.web.servlet.ModelAndView;
public class RequestMappingHandlerAdapterTests {
private static int RESOLVER_COUNT;
private static int INIT_BINDER_RESOLVER_COUNT;
private static int HANDLER_COUNT;
private RequestMappingHandlerAdapter handlerAdapter;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private StaticWebApplicationContext webAppContext;
@BeforeClass
public static void setupOnce() {
RequestMappingHandlerAdapter adapter = new RequestMappingHandlerAdapter();
adapter.setApplicationContext(new StaticWebApplicationContext());
adapter.afterPropertiesSet();
RESOLVER_COUNT = adapter.getArgumentResolvers().getResolvers().size();
INIT_BINDER_RESOLVER_COUNT = adapter.getInitBinderArgumentResolvers().getResolvers().size();
HANDLER_COUNT = adapter.getReturnValueHandlers().getHandlers().size();
}
@Before
public void setup() throws Exception {
this.webAppContext = new StaticWebApplicationContext();
this.handlerAdapter = new RequestMappingHandlerAdapter();
this.handlerAdapter.setApplicationContext(new GenericWebApplicationContext());
this.handlerAdapter.setApplicationContext(this.webAppContext);
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
}
@@ -105,7 +111,7 @@ public class RequestMappingHandlerAdapterTests {
HandlerMethodArgumentResolver redirectAttributesResolver = new RedirectAttributesMethodArgumentResolver();
HandlerMethodArgumentResolver modelResolver = new ModelMethodProcessor();
HandlerMethodReturnValueHandler viewHandler = new ViewNameMethodReturnValueHandler();
this.handlerAdapter.setArgumentResolvers(Arrays.asList(redirectAttributesResolver, modelResolver));
this.handlerAdapter.setReturnValueHandlers(Arrays.asList(viewHandler));
this.handlerAdapter.setIgnoreDefaultModelOnRedirect(true);
@@ -124,7 +130,7 @@ public class RequestMappingHandlerAdapterTests {
HandlerMethodArgumentResolver resolver = new ServletRequestMethodArgumentResolver();
this.handlerAdapter.setCustomArgumentResolvers(Arrays.asList(resolver));
this.handlerAdapter.afterPropertiesSet();
assertTrue(this.handlerAdapter.getArgumentResolvers().getResolvers().contains(resolver));
assertMethodProcessorCount(RESOLVER_COUNT + 1, INIT_BINDER_RESOLVER_COUNT + 1, HANDLER_COUNT);
}
@@ -143,7 +149,7 @@ public class RequestMappingHandlerAdapterTests {
HandlerMethodArgumentResolver resolver = new ServletRequestMethodArgumentResolver();
this.handlerAdapter.setInitBinderArgumentResolvers(Arrays.<HandlerMethodArgumentResolver>asList(resolver));
this.handlerAdapter.afterPropertiesSet();
assertMethodProcessorCount(RESOLVER_COUNT, 1, HANDLER_COUNT);
}
@@ -156,7 +162,7 @@ public class RequestMappingHandlerAdapterTests {
assertTrue(this.handlerAdapter.getReturnValueHandlers().getHandlers().contains(handler));
assertMethodProcessorCount(RESOLVER_COUNT, INIT_BINDER_RESOLVER_COUNT, HANDLER_COUNT + 1);
}
@Test
public void setReturnValueHandlers() {
HandlerMethodReturnValueHandler handler = new ModelMethodProcessor();
@@ -166,19 +172,31 @@ public class RequestMappingHandlerAdapterTests {
assertMethodProcessorCount(RESOLVER_COUNT, INIT_BINDER_RESOLVER_COUNT, 1);
}
@Test
public void modelAttributeAdvice() throws Exception {
this.webAppContext.registerSingleton("maa", ModelAttributeAdvice.class);
this.webAppContext.refresh();
HandlerMethod handlerMethod = handlerMethod(new SimpleController(), "handle");
this.handlerAdapter.afterPropertiesSet();
ModelAndView mav = this.handlerAdapter.handle(this.request, this.response, handlerMethod);
assertEquals("globalAttrValue", mav.getModel().get("globalAttr"));
}
private HandlerMethod handlerMethod(Object handler, String methodName, Class<?>... paramTypes) throws Exception {
Method method = handler.getClass().getDeclaredMethod(methodName, paramTypes);
return new InvocableHandlerMethod(handler, method);
}
private void assertMethodProcessorCount(int resolverCount, int initBinderResolverCount, int handlerCount) {
assertEquals(resolverCount, this.handlerAdapter.getArgumentResolvers().getResolvers().size());
assertEquals(initBinderResolverCount, this.handlerAdapter.getInitBinderArgumentResolvers().getResolvers().size());
assertEquals(handlerCount, this.handlerAdapter.getReturnValueHandlers().getHandlers().size());
}
@SuppressWarnings("unused")
private static class SimpleController {
@@ -189,7 +207,7 @@ public class RequestMappingHandlerAdapterTests {
@SessionAttributes("attr1")
private static class SessionAttributeController {
@SuppressWarnings("unused")
public void handle() {
}
@@ -197,11 +215,20 @@ public class RequestMappingHandlerAdapterTests {
@SuppressWarnings("unused")
private static class RedirectAttributeController {
public String handle(Model model) {
model.addAttribute("someAttr", "someAttrValue");
return "redirect:/path";
}
}
@ControllerAdvice
private static class ModelAttributeAdvice {
@ModelAttribute
public void addAttributes(Model model) {
model.addAttribute("globalAttr", "globalAttrValue");
}
}
}