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

@@ -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");
}
}
}