设为首页 加入收藏

TOP

springboot中使用aop技术
2019-09-03 02:51:45 】 浏览:15
Tags:springboot 使用 aop 技术

aop是面向切面编程的意思,它可以需要先选择一些切入点,然后对这些切入点进行拦截,注入统一的代码逻辑,这也是解耦的一种方式,也是为了避免重复的代码,让开发人员把关注点放在业务上。

引用包

'org.springframework.boot:spring-boot-starter-aop'

添加切入点

/**
 * 基于com.lind.basic.controller包下的方法进行拦截.
 */
@Aspect
@Component
public class AopPrintConstController {
  private static final Logger logger = LoggerFactory.getLogger(AopPrintConstController.class);

  /**
   * 横切点,哪些方法需要被横切.
   */
  @Pointcut(value = "execution(public * com.lind.basic.controller..*.*(..))")
  public void cutOffPoint() {
  }

  /**
   * @param joinPoint 具体的方法之前执行.
   */
  @Before("cutOffPoint()")
  public void doBefore(JoinPoint joinPoint) throws Throwable {
    logger.info("cutOffPoint.before...");
    ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = requestAttributes.getRequest();
    String requestURI = request.getRequestURI();
    String remoteAddr = request.getRemoteAddr();   //这个方法取客户端ip"不够好"
    String requestMethod = request.getMethod();
    String declaringTypeName = joinPoint.getSignature().getDeclaringTypeName();
    String methodName = joinPoint.getSignature().getName();
    Object[] args = joinPoint.getArgs();
    logger.info("请求url=" + requestURI + ",客户端ip=" + remoteAddr + ",请求方式=" + requestMethod + ",请求的类名=" + declaringTypeName + ",方法名=" + methodName + ",入参=" + args);

  }

  /**
   * 解用于获取方法的返回值.
   *
   * @param obj 返回值
   */
  @AfterReturning(returning = "obj", pointcut = "cutOffPoint()")
  public void doBefore(Object obj) throws Throwable {
    logger.info("RESPONSE : " + obj);
  }


}

测试

当我们访问controller下的接口下,在控制台中将输出方法执行前和执行后的结果

com.lind.basic.AopPrintConstController   : 请求url=/hello/1,客户端ip=0:0:0:0:0:0:0:1,请求方式=GET,请求的类名=...
com.lind.basic.controller.H com.lind.basic.AopPrintConstController   : RESPONSE : <200 OK,com.lind.basic.entity.Token@249f92d9,{}>

感想

事实上,springboot真的是一个强大的脚手架,它帮助我们把很多依赖都结合了,像今天说的aop,事实上springboot帮我们把以下包都结合在一起了,让开发人员引用时更方便。

springboot-aop集成了

  • spring-aop,
  • aspectjrt,
  • spectjweaver
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇递归的理解与应用 下一篇最全面的阿里多线程面试题,你能..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目