项目中的一些实用工具

131 阅读1分钟

1、接口的耗时统计

切面+ThreadLocal

2、接口的异常捕获处理

a、使用Spring AOP实现,@Aspect@ComComponent

b、@ControllerAdvice+@ResponseBody@ExceptionHandler(value = Exception.class)组合

3、日志的打印

4、接口的限流

推荐使用过滤器

5、权限控制

使用拦截器实现,继承HandlerInterceptorAdapter

6、对接口的返回做统一的包装处理

使用Spring AOP实现,@Aspect、@ComComponent

针对以上场景,对于过滤器、拦截器、AOP如何选择?

1、使用过滤器的三种方式

a、实现Filter接口,标注@Component注解

b、实现Filter接口,标注@WebFilter注解并在配置类上标注@ServletComponentScan注解,可以自定义url等自定义配置

c、实现Filter接口,定义FilterRegistrationBean的Bean,也可以自定义url等自定义配置

2、使用拦截器

实现HandlerInterceptor接口,并在实现WebMvcConfigurer的实现类中添加拦截器

3、AOP

@Aspect+@PointCut+切点表达式+各种通知

4、执行流程

启动时执行过滤器的init方法--》
doFilter方法--》
拦截器的preHandle--》
@Around 进入--》
@Before--》
实际逻辑--》
@AfterReturning--》
@after--》
@Around 结束--》
postHandle--》
afterCompletion