Springboot使用MethodInterceptor和切面统一打印service层信息

package org.example.interc;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class ServiceInterceptor implements MethodInterceptor {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    public ServiceInterceptor() {
    }

    public Object invoke(MethodInvocation invocation) throws Throwable {
        long startTimeMillis = System.currentTimeMillis();
        long endTimeMillis = 0L;
        String className = invocation.getThis().getClass().getSimpleName();
        String interfaceFullName = invocation.getThis().getClass().getName();
        String methodName = invocation.getMethod().getName();
        String txName = "交易:" + className + "." + methodName;

        try {
            Class<?>[] interfaces = invocation.getThis().getClass().getInterfaces();
            if (interfaces != null && interfaces.length > 0) {
                interfaceFullName = interfaces[0].getName();
            }
        } catch (Exception var15) {
            this.logger.warn("获取接口名称异常", var15);
        }

        Object[] args = invocation.getArguments();
        boolean noArgs = false;
        if (args == null || args.length < 1 || args[0] == null) {
            noArgs = true;
        }

        try {
            if (!noArgs) {
                CheckInputUtil.validate(args[0]);
            }

            Object returnObj = invocation.proceed();
            endTimeMillis = System.currentTimeMillis();
            this.logger.info(txName + " success ,耗时:" + (endTimeMillis - startTimeMillis) + "ms");
            return returnObj;
        } catch (Exception var16) {
            endTimeMillis = System.currentTimeMillis();
            if (var16 instanceof ServiceException) {
                ServiceException serE = (ServiceException) var16;
                if (StringUtils.length(serE.getCode()) < 10) {
                    this.logger.error("业务异常:" + serE.getExtMsg(), serE);
                    this.logger.info(txName + " failure ,耗时:" + (endTimeMillis - startTimeMillis) + "ms");
                } else {
                    String logLevel = serE.getCode().substring(5, 6);
                    if ("E".equals(logLevel)) {
                        this.logger.error("业务异常:" + serE.getExtMsg(), serE);
                        this.logger.info(txName + " failure ,耗时:" + (endTimeMillis - startTimeMillis) + "ms");
                    } else if (CommonErrorCode.ALARM.getCode().equals(serE.getCode())) {
                        this.logger.error("业务异常: alarm[" + serE.getExtMsg() + "]", serE);
                        this.logger.info(txName + " alarm ,耗时:" + (endTimeMillis - startTimeMillis) + "ms");
                    } else {
                        this.logger.warn("业务告警:" + serE.getExtMsg());
                        this.logger.info(txName + " warn ,耗时:" + (endTimeMillis - startTimeMillis) + "ms");
                    }
                }
            } else {
                this.logger.error("未知异常:", var16);
                this.logger.info(txName + " failure ,耗时:" + (endTimeMillis - startTimeMillis) + "ms");
            }

            throw var16;
        }
    }
}
import lombok.extern.slf4j.Slf4j;
import org.example.interc.ServiceInterceptor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnProperty(name = "aop.exception.pointcut", matchIfMissing = true)
@Slf4j
public class ServiceAopConfig {


    // 带任何参数的service包下的接口
    @Value("${aop.pointcut:execution(* org.example.service..*(..))}")
    private String expression;

    /**
     * 异常的切面
     *
     * @return
     */
    @Bean
    public DefaultPointcutAdvisor defaultPointcutAdvisor2() {
        // 声明切点
        //JdkRegexpMethodPointcut pointcut = new JdkRegexpMethodPointcut();
        //pointcut.setPatterns("com.example.*");
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        // 拦截org.example.service包和子包下带一个参数的任何方法
        //pointcut.setExpression("execution(* org.example.service..*(*))");
        pointcut.setExpression(expression);

        // 声明增强
        ServiceInterceptor interceptor = new ServiceInterceptor();

        // 配置切面
        DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor();
        advisor.setPointcut(pointcut);
        advisor.setAdvice(interceptor);
        return advisor;
    }
}

相关统一配置:

public class ServiceException extends RuntimeException {
    private static final long serialVersionUID = 6514891174875747380L;
    private String code;
    private String msg;
    private String extMsg;
    private Object[] param = null;

    public ServiceException(ErrorCode errorCode, String[] param, String... extMsg) {
        super(null == errorCode ? "" : errorCode.getCode());
        this.init(errorCode, param, extMsg);
    }

    private void init(ErrorCode errorCode, Object[] param, String... extMsg) {
        if (null != errorCode) {
            this.code = null == errorCode ? "" : errorCode.getCode();
            String msgPatten = null == errorCode ? "" : Property.getProperty(errorCode.getCode());
            msgPatten = msgPatten == null ? "" : msgPatten;
            this.msg = null == errorCode ? "" : MessageFormat.format(msgPatten, param);
            StringBuilder builder = new StringBuilder(100);
            builder.append(this.msg);
            if (null != extMsg) {
                String[] var6 = extMsg;
                int var7 = extMsg.length;

                for(int var8 = 0; var8 < var7; ++var8) {
                    String ext = var6[var8];
                    builder.append("[").append(ext).append("]");
                }
            }

            this.extMsg = builder.toString();
            this.param = param;
        }
    }

    public ServiceException(String code, String msg) {
        super(code + ":" + msg);
        this.code = code;
        this.msg = msg;
    }

    public ServiceException(ErrorCode errorCode, Throwable e, String[] param, String... extMsg) {
        super(null == errorCode ? "" : errorCode.getCode(), e);
        this.init(errorCode, param, extMsg);
    }

    public String getCode() {
        return this.code;
    }

    public String getMsg() {
        return this.msg;
    }

    public String getExtMsg() {
        return this.extMsg;
    }

    public Object[] getParam() {
        return this.param;
    }

    public String getMessage() {
        return super.getMessage() + "," + this.extMsg;
    }

    public static void main(String[] args) {
    }
}


public interface ErrorCode {
    String getCode();
}


public enum CommonErrorCode implements ErrorCode {
    ALARM("COMCCF0000"),
    SUCCESS("COMCC00000"),
    UNKHOWN_ERROR("COMCCES999"),
    TIMEOUT_ERROR("COMCCEB888"),
    ERROR_NULL_RECORD("COMCCWB888"),
    ERROR_WHITELIST("COMCCWB887"),
    NULL_PROPERTIES("COMCCWBA01"),;


    private String code;

    private CommonErrorCode(String code) {
        this.code = code;
    }

    public String getCode() {
        return this.code;
    }
}

public class CheckInputUtil {
    private static String SPLIT_STRING = "\\.";

    public CheckInputUtil() {
    }

    public static void validate(Object bean) {
        validate(bean, SPLIT_STRING);
    }

    public static void validate(Object bean, String splitStr) {
        if (null == bean) {
            throw new ServiceException(CommonErrorCode.NULL_PROPERTIES, new String[]{"请求对象"}, new String[0]);
        } else {
            String msg = ValidateEntityUtil.validate(bean, new Class[0]);
            if (!StringUtils.isBlank(msg)) {
                String[] msgArray = msg.split("##");
                String[] msgArray2 = msgArray[0].split(splitStr);
                if (msgArray2.length != 2) {
                    throw new ServiceException(CommonErrorCode.UNKHOWN_ERROR, new String[]{msgArray[0]}, new String[]{"解析验证的返回信息失败!hibernate validate返回信息:" + msg});
                } else {
                    try {
                        throw new ServiceException(CommonErrorCode.valueOf(msgArray2[1]), new String[]{msgArray[1]}, new String[]{msgArray[2]});
                    } catch (ServiceException var6) {
                        throw var6;
                    } catch (Exception var7) {
                        throw new ServiceException(CommonErrorCode.UNKHOWN_ERROR, var7, (String[])null, new String[]{"输入验证失败!验证的hibernate validate返回信息:" + msg});
                    }
                }
            }
        }
    }
}


package org.example.interc;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import org.apache.commons.lang3.StringUtils;

public class ValidateEntityUtil {
    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    public ValidateEntityUtil() {
    }

    public static String validate(Object obj, Class<?>... groups) {
        Set<Field> fields = getFieldsOfThisAndSuper(obj);
        Iterator<ConstraintViolation<Object>> iter = null;
        Iterator var4 = fields.iterator();

        while(var4.hasNext()) {
            Field field = (Field)var4.next();
            boolean isSkip = true;
            Annotation[] var7 = field.getAnnotations();
            int var8 = var7.length;

            for(int var9 = 0; var9 < var8; ++var9) {
                Annotation anno = var7[var9];
                if (anno.annotationType().getName().indexOf("org.hibernate.validator") != -1 || anno.annotationType().getName().indexOf("javax.validation") != -1) {
                    isSkip = false;
                    break;
                }
            }

            if (!isSkip) {
                iter = validator.validateProperty(obj, field.getName(), groups).iterator();
                if (iter.hasNext()) {
                    String msg = ((ConstraintViolation)iter.next()).getMessage();
                    field.setAccessible(true);
                    Object fieldValue = null;

                    try {
                        fieldValue = field.get(obj);
                    } catch (Exception var11) {
                        fieldValue = null;
                    }

                    msg = StringUtils.isBlank(msg) ? field.getName() + "##the value of property[" + field.getName() + "], is invalid!" : msg + "##" + field.getName() + "##fieldName=" + field.getName() + ",fieldValue=" + fieldValue;
                    return msg;
                }
            }
        }

        return null;
    }

    private static Set<Field> getFieldsOfThisAndSuper(Object obj) {
        Class<?> superClass = obj.getClass().getSuperclass();
        Field[] fieldsOfSuper = superClass == null ? null : obj.getClass().getSuperclass().getDeclaredFields();
        Field[] fieldsOfThis = obj.getClass().getDeclaredFields();
        Set<Field> fields = new HashSet();
        Field[] var5;
        int var6;
        int var7;
        Field field;
        if (fieldsOfSuper != null) {
            var5 = fieldsOfSuper;
            var6 = fieldsOfSuper.length;

            for(var7 = 0; var7 < var6; ++var7) {
                field = var5[var7];
                fields.add(field);
            }
        }

        var5 = fieldsOfThis;
        var6 = fieldsOfThis.length;

        for(var7 = 0; var7 < var6; ++var7) {
            field = var5[var7];
            fields.add(field);
        }

        return fields;
    }
}

package org.example.interc;

import java.util.Properties;

public class Property {
    private static Properties property;

    private Property() {
    }

    static void init(Properties props) {
        property = props;
    }

    public static String getProperty(String key) {
        return key == null ? null : property.getProperty(key);
    }

    public static String getProperty(String key, String defaultValue) {
        return property.getProperty(key, defaultValue);
    }

    public static Properties getAllProperty() {
        return property;
    }
}

参考:使用spring的MethodInterceptor实现aop功能的三种方式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值