springboot中使用aop技術

aop是面向切面編程的意思,它能夠須要先選擇一些切入點,而後對這些切入點進行攔截,注入統一的代碼邏輯,這也是解耦的一種方式,也是爲了不重複的代碼,讓開發人員把關注點放在業務上。spring

引用包

'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

springboot-aop集成了spring-boot

  • spring-aop,
  • aspectjrt,
  • spectjweaver
相關文章
相關標籤/搜索