pan*_*j12 9 java spring spring-mvc
双方HandlerInterceptor并HandlerInterceptorAdaptor具有preHandle和postHandle方法.但我无法理解它们在实施方面有何区别.
Ali*_*ani 23
编程到接口而不是实现是一个很好的做法,Spring Framework通过提供相当多的这些接口来使用这种做法,HandlerInterceptor就是其中之一.其中一些接口比其他接口更丰富.因此,如果您作为客户端想要为他们提供自定义实现并且只关心他们的一些方法,那么最终会有一些实际的实现和许多空实现.
例如,假设您要为preHandle方法提供实现,而不关心其他两个.不幸的是,你应该为其他两个提供一些空的实现:
public class CustomHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
// Some complex logic
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) throws Exception {
}
}
Run Code Online (Sandbox Code Playgroud)
那些空的实现会造成较大的样板代码,当你实现更丰富的接口,像WebMvcConfigurer与10+抽象方法,想象的空方法的负荷.
为了解决这个问题,Spring框架通常提供对应的抽象适配器为这些接口,如HandlerInterceptorAdaptor用于HandlerInterceptor接口或WebMvcConfigurerAdapter为WebMvcConfigurer.这些适配器只是这些接口的所有方法的一组默认和简化实现.您可以使用提供的适配器重构前面的代码:
public class CustomHandlerInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
// Some complex logic
}
}
Run Code Online (Sandbox Code Playgroud)
由于这些空实现是由HandlerInterceptorAdapter类提供的,因此您只需提供preHandle方法的实现.
正如我所说,这是Spring Framework中反复出现的主题,一些常见的例子是:
HandlerInterceptor是interface定义工作合同的。它具有3需要实现的抽象方法。
即使您只需要拦截afterCompletion,您仍然需要2空方法!
用Spring的话来说,“适配器”是abstract class为所有方法创建默认的空实现,因此您只需要覆盖所需的方法即可。请注意,这早于Java 8 default方法,该方法将使其变得多余。
如果你只需要preHandle和postHandle功能,那么你应该使用HandlerInterceptorAdaptor,你只需要重写这两个方法。如果使用Plain HandlerInterceptor,则仍需要一个空方法来编译代码-这是不必要的样板。
由于java 8为接口方法提供了一个很好的默认实现特性,新版本spring中的接口不需要适配器类来提供接口的默认实现。
所以,我们可以直接实现接口,只覆盖接口中需要的方法,而不用为spring接口扩展相应的适配器类。
例如,如果你检查HandlerInterceptor接口的声明,它的所有方法都有空的实现,所以不需要它的适配器 cass HandlerInterceptorAdapter