SpringBoot系列——aop 面向切面

  前言

  項目中咱們常常會用到aop切面,好比日誌記錄;這裏簡單記錄一下springboot是如何使用aophtml

   spring對aop的配置,來自springboot參考手冊,Common application properties:https://docs.spring.io/spring-boot/docs/2.1.0.RELEASE/reference/htmlsingle/#common-application-propertiesgit

# AOP
spring.aop.auto=true # Add @EnableAspectJAutoProxy.
spring.aop.proxy-target-class=true # Whether subclass-based (CGLIB) proxies are to be created (true), as opposed to standard Java interface-based proxies (false).

 

  maven引包

        <!--aop 面向切面-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
<!--slf4j-log4j12 日誌管理--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> </dependency>

 

  Aspect 切面

/**
 * Aspect 切面
 * 日誌切面
 */
@Aspect
@Component
public class LogAspect {

    /**
     * slf4j日誌
     */
    private final static Logger logger = LoggerFactory.getLogger(LogAspect.class);

    /**
     * Pointcut 切入點
     * 匹配cn.controller包下面的全部方法
     */
    @Pointcut("execution(public * cn.controller.*.*(..))")
    public void webLog(){}

    /**
     * 環繞通知
     */
    @Around(value = "webLog()")
    public Object arround(ProceedingJoinPoint pjp) {
        try {
            logger.info("一、Around:方法環繞開始.....");
            Object o =  pjp.proceed();
            logger.info("三、Around:方法環繞結束,結果是 :" + o);
            return o;
        } catch (Throwable e) {
            logger.error(pjp.getSignature() + " 出現異常: ", e);
            return Result.of(null, false, "出現異常:" + e.getMessage());
        }
    }

    /**
     * 方法執行前
     */
    @Before(value = "webLog()")
    public void before(JoinPoint joinPoint){
        logger.info("二、Before:方法執行開始...");
        // 接收到請求,記錄請求內容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();
        // 記錄下請求內容
        logger.info("URL : " + request.getRequestURL().toString());
        logger.info("HTTP_METHOD : " + request.getMethod());
        logger.info("IP : " + request.getRemoteAddr());
        logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));

    }

    /**
     * 方法執行結束,無論是拋出異常或者正常退出都會執行
     */
    @After(value = "webLog()")
    public void after(JoinPoint joinPoint){
        logger.info("四、After:方法最後執行.....");
    }

    /**
     * 方法執行結束,加強處理
     */
    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret){
        // 處理完請求,返回內容
        logger.info("五、AfterReturning:方法的返回值 : " + ret);
    }

    /**
     * 後置異常通知
     */
    @AfterThrowing(value = "webLog()")
    public void throwss(JoinPoint joinPoint){
        logger.error("AfterThrowing:方法異常時執行.....");
    }
}

 

   效果

  訪問獲取全部用戶接口github

 

  代碼開源

  代碼已經開源、託管到個人GitHub、碼雲:web

  GitHub:https://github.com/huanzi-qch/springBootspring

  碼雲:https://gitee.com/huanzi-qch/springBootapi

相關文章
相關標籤/搜索