美文网首页
Springboot Aop 编程

Springboot Aop 编程

作者: 夜空最亮的9星 | 来源:发表于2019-12-17 14:03 被阅读0次

首先,引入依赖


    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

    </dependencies>


    <build>
        <plugins>
            <!-- 编译期织入 -->
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>aspectj-maven-plugin</artifactId>
                <version>1.11</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>test-compile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

声明Log

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {
    String value() default "";
}

定义log切面类:

import com.goodwin.apo.Log;
import com.goodwin.domain.LogVo;
import com.goodwin.entity.UserInfo;
import com.goodwin.service.LogService;
import com.goodwin.util.SessionUtil;
import io.netty.util.internal.ThrowableUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;



@Component
@Aspect
@Slf4j
public class LogAspect {

    @Autowired
    private LogService logService;

    private long currentTime = 0L;

    /**
     * 配置切入点
     */
    @Pointcut("@annotation(com.goodwin.apo.Log)")
    public void logPointcut() {
        // 该方法无方法体,主要为了让同类中其他方法使用此切入点
    }

    /**
     * 配置环绕通知,使用在方法logPointcut()上注册的切入点
     *
     * @param joinPoint join point for advice
     */
    @Around("logPointcut()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result = null;
        currentTime = System.currentTimeMillis();
        result = joinPoint.proceed();

        try {
            saveLog(joinPoint,currentTime,"INFO",null);
        }catch (Exception e){
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 配置异常通知
     *
     * @param joinPoint join point for advice
     * @param e exception
     */
    @AfterThrowing(pointcut = "logPointcut()", throwing = "e")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {

        byte[] bytes = ThrowableUtil.stackTraceToString(e).getBytes();
        currentTime = System.currentTimeMillis();

        try {
            saveLog(joinPoint,currentTime,"ERROR",bytes);
        }catch (Exception e1){
            e1.printStackTrace();
        }
    }

    private void saveLog(JoinPoint joinPoint, long time,String logType,byte[] bytes){

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Log logAnn = method.getAnnotation(Log.class);
        LogVo  logger = new LogVo();
        logger.setLogType(logType);
        logger.setExceptionDetail(bytes);
        logger.setTime(System.currentTimeMillis() - time);

        if (logAnn!=null){
            logger.setDescription(logAnn.value());
        }

        UserInfo userInfo = SessionUtil.getInstance().getSession();

        if (userInfo!=null){
            logger.setUsername(userInfo.getName());
            logger.setUserType(userInfo.getUserType());
        }else {
            logger.setUsername("未登录");
//            logger.setUserType(1000);
        }


//        // 方法的 类名、方法名
//        String className = joinPoint.getTarget().getClass().getName();


        String methodName = signature.getName();
        logger.setMethod(methodName);

        //请求的参数
        StringBuffer params = new StringBuffer("{");
        //参数值
        Object[] argValues = joinPoint.getArgs();
        //参数名称
        String[] argNames = ((MethodSignature)joinPoint.getSignature()).getParameterNames();
        if(argValues != null){
            for (int i = 0; i < argValues.length; i++) {
//                params += " " + argNames[i] + ": " + argValues[i];
                params.append(" ")
                        .append(argNames[i])
                        .append(": ")
                        .append(argValues[i])
                        .append(",");
            }
        }

        params.append(" }");
        logger.setParams(params.toString());
        logService.save(logger);
    }
}

参考链接:https://github.com/zolagz/springboot-aop-aspect

相关文章

网友评论

      本文标题:Springboot Aop 编程

      本文链接:https://www.haomeiwen.com/subject/jbpsnctx.html