当控制器实现接口时,不会调用Spring @ExceptionHandler

时间:2014-08-14 14:41:54

标签: java spring spring-mvc

我有@Controller实现了一个接口,但是没有执行抽象@ExceptionHandler上的BaseController方法。

我已经调试了,似乎AnnotationMethodHandlerExceptionResolver有这一行试图找到带注释的方法

ExceptionHandler exceptionHandler 
    = AnnotationUtils.findAnnotation(method, ExceptionHandler.class);

但它只传递了接口上的方法,我无法将方法添加到此接口。

Spring会这样做

final Class<?> handlerType = ClassUtils.getUserClass(handler);

然后在迭代可用方法时使用handlerType。

ClassUtils.getUserClass(handler) -

的文档
  

返回给定实例的用户定义类:通常很简单   给定实例的类,但是在原始类的情况下   CGLIB生成的子类。

其中handle实际上是我的控制器implamentation类,但最后是代理。

使用Spring 3.2,使用context:component-scan注册控制器。所以我的问题,如果不是很明显,我如何让Spring调用异常处理程序方法?

interface ControllerInterface {
   String doStuff();
}

@Controller
public class Controller extends BaseController implements ControllerInterface {

  public String doStuff() {
     throw new ServiceException();
  }

}

public class BaseController {

    @ExceptionHandler(ServiceException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public Error handleException(ServiceException exp) {

        return new Error(exp.getCode(), exp.getMessage());
    }
}

0 个答案:

没有答案
相关问题