spring aop

128 阅读1分钟

aop切面

package com.yutoo.fwk.admarketing.sync.aspects;

import com.yutoo.fwk.base.common.entity.R;
import com.yutoo.fwk.base.common.exception.YtException;
import com.yutoo.fwk.constants.ResultVO;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author The One
 * 2021/9/18  9:16
 */
@Aspect
@Component
public class ExceptionAspect {

    private final static Logger LOGGER = LoggerFactory.getLogger(ExceptionAspect.class);

    /**
     * 切点
     */
    @Pointcut("execution(* com.yutoo.fwk.admarketing.sync.provider.facebook.*.*(..))")
    public void log() {

    }

    /**
     * 执行方法前
     * @param joinPoint
     */
    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
//        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        HttpServletRequest request = attributes.getRequest();
//        //url
//        LOGGER.debug("url={}", request.getRequestURL());
//        //method
//        LOGGER.info("method={}", request.getMethod());
//        //ip
//        LOGGER.info("id={}", request.getRemoteAddr());
//        //class_method
//        LOGGER.info("class_method={}", joinPoint.getSignature().getDeclaringTypeName() + "," + joinPoint.getSignature().getName());
//        //args[]
//        LOGGER.info("args={}", joinPoint.getArgs());
    }

    /**
     * 执行方法时
     * @param proceedingJoinPoint
     * @return
     * @throws Throwable
     */
    @Around("log()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
//        System.out.println("进入环绕");
        try {
            return proceedingJoinPoint.proceed();
        } catch (NullPointerException e) {
            throw new YtException(ResultVO.FBERROR);
        } catch (YtException e) {
            throw e;
        } catch (Exception e) {
//            System.out.println("异常");
            return R.error();
//            return new Exception("异常");
        }
//        if (result == null) {

//        } else {
//            return result;
//        }
    }

    /**
     * 执行方法后
     * @param object
     */
    @AfterReturning(pointcut = "log()", returning = "object")//打印输出结果
    public void doAfterReturing(Object object) {
//        LOGGER.info("response={}", object.toString());
    }
}