aop通过自定义注解记录日志

package com.znlh.tms.calc.web.security;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author :ZhangWenQiang
 *
 * 记录系统日志
 */

@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface LogRecordAnnotation {

    /**
     * 操作方法
     */
    String operateMethod() default "";
    /**
     * 操作内容
     */
    String operationContent() default "";

}

  

package com.znlh.tms.calc.aop;

import com.znlh.tms.calc.web.security.LogRecordAnnotation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.messaging.handler.HandlerMethod;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author :ZhangWenQiang
 */
@Aspect
@Component
@Slf4j
public class LogRecordAspect {

    /**
     * 切入点
     */
    @Pointcut("@annotation(com.znlh.tms.calc.web.security.LogRecordAnnotation)")
    public void pointcut(){}

    /**
     * 前置通知
     *
     * @param joinPoint
     */
    @Before(value = "pointcut()")
    public void doBefore(JoinPoint joinPoint){
       log.info("方法:"+joinPoint.getSignature()+"执行");
    }

    /**
     * 后置通知:方法正常返回才执行
     *
     * @param joinPoint
     */
    @AfterReturning
    public void doAfter(JoinPoint joinPoint){

        //获取自定义注解
        LogRecordAnnotation annotation = ((MethodSignature)joinPoint.getSignature())
                                                .getMethod().getAnnotation(LogRecordAnnotation.class);
        //操作
        String method = annotation.operateMethod();
        //内容
        String operationContent = annotation.operationContent();
        //操作时间
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        dtf.format(now);

        //获取到所有的参数值的数组
        Object[] args = joinPoint.getArgs();
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        //获取到方法的所有参数名称
        String[] parameterNames = methodSignature.getParameterNames();

    }


    @AfterThrowing
    public void doThrowing(){
        log.error("方法执行失败");
    }
}

 

posted @ 2020-03-21 16:52  似清风  阅读(370)  评论(0)    收藏  举报