Spring 4中的ControllerAdvice注释不起作用

时间:2018-10-02 16:49:43

标签: spring spring-mvc

在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版本。

1 个答案:

答案 0 :(得分:1)

通过添加以下内容在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!