[英]ControllerAdvice annotation in spring 4 is not working
在spring-mvc.xml中:
<beans ...>
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />
<bean class="com.app.controllers.ExceptionController"/>
....
</beans>
在GlobalException.java中:
@ControllerAdvice(basePackages = "com.exceptions")
public class GlobalException {
@ExceptionHandler(UserDefinedException.class)
public ModelAndView processCustomException(UserDefinedException ud) {
ModelAndView mav = new ModelAndView("exceptionPage");
mav.addObject("name", ud.getName());
mav.addObject("message", ud.getMessage());
return mav;
}
}
在ExceptionController.java中:
public class ExceptionController implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
throw new UserDefinedException("Custom Exception has occured", "CustomException");
}
}
Ecxception拋出com.exceptions.UserDefinedException: Custom Exception has occured
。 但是不調用ExceptionHandler方法。 這段代碼出了什么問題。 我正在使用Spring 4.3版本。
通過添加以下代碼,在spring-mvc.xml中啟用Spring的組件掃描:
<context:component-scan base-package="com.exceptions" />
並刪除您配置的過時XML配置的Spring bean( <bean class="com.app.controllers.ExceptionController"/>
)
還可以使用@Controller
注釋控制器類,並向控制器方法添加@RequestMapping
,例如:
@Controller
public class ExceptionController {
@RequestMapping(value="/whatever", method=RequestMethod.GET)
public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
throw new UserDefinedException("Custom Exception has occured", "CustomException");
}
}
這樣,應該在應用程序啟動時由Spring本身找到,實例化帶有Spring構造型注釋(@ Component,@ Service,@ Controller,@ Repository)的類,並將其注冊為Spring Bean!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.