SpringBoot的拦截机制实现不是其特有的,它和Spring中一致,都可以使用下面三种技术来实现拦截机制
- 过滤器(Filter)
- 拦截器(Interceptor)
- 切片(Aspect)
过滤器拦截
过滤器是servlet中的技术,在SpringBoot中,我们只需要定义一个过滤器类它就能自动生效。
@Component
public class TimeFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("TimeFilter init");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
System.out.println("TimeFilter doFilter");
long startTime = System.currentTimeMillis();
filterChain.doFilter(servletRequest,servletResponse);
System.out.println("【Filter】耗时;"+(System.currentTimeMillis()-startTime));
}
@Override
public void destroy() {
System.out.println("TimeFilter destory");
}
}
如果要对过滤器进行一些配置,如:配置拦截路径,可以在配置类中进行定义声明
@Bean
public FilterRegistrationBean timeFilter(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
TimeFilter timeFilter = new TimeFilter();
registrationBean.setFilter(timeFilter);
List<String> urlList = new ArrayList<>();
urlList.add("/*");
//配置Filter拦截的路径
registrationBean.setUrlPatterns(urlList);
return registrationBean;
}
拦截器拦截
假设我们现在需要时间一个功能:统计每个方法的执行所花费的时间。首先我们要定义一个拦截器类,该类是HandlerInterceptor
的子类,实现如下
public class TimeInterceptor implements HandlerInterceptor {
private Logger log = LoggerFactory.getLogger(TimeInterceptor.class) ;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
long startTime = System.currentTimeMillis();
request.setAttribute("startTime", startTime);
// 返回true表示将请求放行
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {
HandlerMethod handlerMethod = (HandlerMethod) o;
long startTime = (Long)request.getAttribute("startTime");
long endTime = System.currentTimeMillis();
long executeTime = endTime - startTime;
log.info("执行{}类的{}方法,花费了:{}",
handlerMethod.getBean().getClass().getSimpleName(),handlerMethod.getMethod().getName(),executeTime);
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
HandlerMethod handlerMethod = (HandlerMethod) o;
log.info("【*** TimeInterceptor.afterCompletion() ***】" + handlerMethod.getBean().getClass().getSimpleName());
}
}
preHandle
在被拦截方法执行之前回调,postHandle
方法在被拦截方法执行之后,跳转页面之前回调,而afterCompletion
方法在跳转页面之后执行。示意图如下
可以看到实现HandlerInterceptor
接口需要实现它的三个方法。如果我们只想实现其中某个方法,可以继承它的适配器类HandlerInterceptorAdapter
。该适配器内部对HandlerInterceptor
接口中的三个方法提供了空实现。
有了拦截器类之后,我们还需要对其进行配置拦截器才能生效。SpringBoot中在配置类中进行拦截器的配置。
@Configuration
public class MyApplicaionConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// MyInterceptor对所有路径进行拦截
registry.addInterceptor(new TimeInterceptor()).addPathPatterns("/**");
super.addInterceptors(registry);
}
}
切片拦截
切片拦截就是常说的AOP
,AOP
是Spring核心之一,下面看看它在SpringBoot环境中是怎样使用
首先要引 入AOP
的依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
然后我们就可以写个AOP的around拦截
@Component
@Aspect
public class ServiceAspect {
private Logger log = LoggerFactory.getLogger(ServiceAspect.class);
@Around("execution(* cn.zgc.springboot.service..*.*(..))")
public Object arroundInvoke(ProceedingJoinPoint point) throws Throwable {
this.log.info("【*** Service-Before ***】执行参数:"
+ Arrays.toString(point.getArgs()));
Object obj = point.proceed(point.getArgs()); // 进行具体业务调用
this.log.info("【*** Service-After ***】返回结果:" + obj);
return obj;
}
}
此时无需其他配置,AOP
的拦截功能就能生效。它能够对cn.zgc.springboot.service
包下所有的方法进行拦截。
网友评论