Spring AOP面向切面编程之自定义日志注解@OperateLog

发布时间:2022-12-04 21:00

金融、交易类应用的日志Log非常重要,这类应用的业务包含了日志记录逻辑,比如记录用户的交易记录。

对于重要的日志数据,我们是一定要持久化到数据库和磁盘上的,还有一些日志的数据,则是为了方便运营人员的操作记录。

Spring AOP面向切面编程非常强大,不论是Spring的声明式事务@Transactional,还是Spring Cloud Hystrix熔断器,都是基于AOP的原理实现的,只要研究一下Spring framework框架的源码,就会明白为什么Spring会那么灵活而敏捷,她的实现是那么优雅,再去看其他框架的源码,比如Mybatis的源码看得我很难受,然而却是很多开发者在用,哪怕是比较少人用的JOOQ都比Mybastic的实现好得多。

Spring AOP原理很简单,我们完全可以利用AOP的特性去开发我们需要的组件,

通过Aspect代理我们真正的业务逻辑对象,添加日志记录的逻辑,只需要在Service层方法上加入@OperateLog注解即可。

@OperateLog注解类


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

/**
 * @author linzihao 
 */
@Target({ElementType.TYPE, ElementType.METHOD}) // 注解类型, 级别
@Retention(RetentionPolicy.RUNTIME) // 运行时注解
public @interface OperateLog {
    Class service() default DefaultOperateLogService.class;
}

AbstractOperateLogService类是对日志逻辑的抽象,作为业务逻辑的一部分。

exceptionHolder用于在业务流程中暂存异常,以便在需要记录操作失败的一些场景,

如果只有操作成功时才记录日志,那么不需要用到exeptionHolder。


import org.aspectj.lang.ProceedingJoinPoint;

/**
 * 记录操作行为
 *
 * @author linzihao
 */
public abstract class AbstractOperateLogService {
    public String LOG_TYPE_UPDATE = "update";
    public String LOG_TYPE_ADD = "add";
    public String LOG_TYPE_DELETE = "delete";
    public static ThreadLocal exceptionHolder = new ThreadLocal<>();

    public void setBusinessThrowable(Throwable e) {
        exceptionHolder.set(e);
    }

    public void completeAndThrow() throws Throwable {
        if (exceptionHolder.get() != null) {
            Throwable throwable = exceptionHolder.get();
            exceptionHolder.remove();
            throw throwable;
        }
    }

    /**
     * 运行业务逻辑并记录日志
     *
     * @param joinPoint
     * @return
     * @throws RuntimeException
     */
    public abstract Object logAround(ProceedingJoinPoint joinPoint) throws Throwable;
}

因为AbstractOperateLogService是抽象类,在@OperateLog注解的定义中需要初始化默认的日志服务对象,所以要实现了DefaultOperateLogService 。

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.stereotype.Component;

/**
 * @author linzihao
 */
@Slf4j
@Component
public class DefaultOperateLogService extends AbstractOperateLogService {
    @Override
    public Object logAround(ProceedingJoinPoint joinPoint) {
        log.info("default OperateLogService logAround run!");
        try {
            return joinPoint.proceed(joinPoint.getArgs());
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return null;
    }
}

Spring AOP的Aspect切面负责调用我们的日志服务类OperateLogService。

import com.ligeit.operate.infrastructure.utils.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author linzihao
 */
@Slf4j
@Aspect // 切面标识
@Component // 交给spring容器管理
public class OperateLogAspect implements ApplicationContextAware {

    /**
     * 选取切入点为自定义注解
     */
    @Pointcut("@annotation(com.ligeit.operate.infrastructure.commons.operatelog.OperateLog)")
    public void OperateLog() {
    }

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public static Method getMethod(JoinPoint joinPoint) throws NoSuchMethodException {
        Signature signature = joinPoint.getSignature();
        if (!(signature instanceof MethodSignature)) {
            log.info("--------{}", "!(signature instanceof MethodSignature)");
            return null;
        }
        MethodSignature methodSignature = (MethodSignature) signature;
        Object target = joinPoint.getTarget();
        // 获取到当前执行的方法
        Method method = target.getClass().getMethod(methodSignature.getName(), methodSignature.getParameterTypes());
        return method;
    }

    private AbstractOperateLogService getService(JoinPoint joinPoint) throws NoSuchMethodException {
        //获取方法
        Method method = getMethod(joinPoint);
        // 获取方法的注解
        OperateLog annotation = method.getAnnotation(OperateLog.class);
        Class service = annotation.service();
        if (!AbstractOperateLogService.class.isAssignableFrom(service)) {
            log.info("--------{}", "必须是实现IOperateLogService接口的类!");
            return null;
        }
        String beanName = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(applicationContext, service)[0];
        return (AbstractOperateLogService) SpringUtils.getBean(beanName);
    }


    @Around(value = "OperateLog()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        return getService(joinPoint).logAround(joinPoint);
    }
}

要让OperateLogService日志服务类生效,要注入到Spring容器中,可以使用@Component,这里我仿造@Component实现自定义的注解,可以标识出被代理的业务Service类。

import org.springframework.core.annotation.AliasFor;
import org.springframework.stereotype.Component;

import java.lang.annotation.*;

/**
 * @author linzihao
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface OpetateLogComponent {
    /**
     * The value may indicate a suggestion for a logical component name,
     * to be turned into a Spring bean in case of an autodetected component.
     * @return the suggested component name, if any (or empty String otherwise)
     */
    @AliasFor(annotation = Component.class)
    String value() default "";
    /**
     * 要记录日志的类
     *
     * @return
     */
    Class location() default DefaultOperateLogService.class;

}

实现我们的OperateLogService日志服务类,这里给出的代码是在生产环境中使用的实际例子。

import com.ligeit.operate.biz.domain.model.ProductDetailDomain;
import com.ligeit.operate.biz.domain.model.ProductUpdateDomain;
import com.ligeit.operate.biz.domain.model.SkuDetailDomain;
import com.ligeit.operate.biz.domain.model.UserInfoDomain;
import com.ligeit.operate.biz.external.api.ProductExternal;
import com.ligeit.operate.biz.service.UserService;
import com.ligeit.operate.infrastructure.commons.interceptor.LoginInterceptor;
import com.ligeit.operate.infrastructure.commons.operatelog.AbstractOperateLogService;
import com.ligeit.operate.infrastructure.commons.operatelog.OpetateLogComponent;
import com.ligeit.operate.infrastructure.persistence.api.entity.ProductSkuOperationLog;
import com.ligeit.operate.infrastructure.persistence.api.mapper.ProductSkuOperationLogMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 商品更新日志
 *
 * @author linzihao
 */
@OpetateLogComponent(location = ProductService.class)
public class ProductUpdateOperateLogServiceImpl extends AbstractOperateLogService {
    @Autowired
    private ProductExternal productExternal;
    @Autowired
    private ProductSkuOperationLogMapper productSkuOperationLogMapper;
    @Autowired
    private UserService userService;

    @Override
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        ProductUpdateDomain updateDetail = (ProductUpdateDomain) args[0];
        ProductDetailDomain beforeDetail = productExternal.getProductDetail(updateDetail.getProductId());
        assert beforeDetail != null;
        Object returnValue = joinPoint.proceed(args);
        if (returnValue == null || returnValue.equals(false)) {
            return returnValue;
        }
        UserInfoDomain user = new UserInfoDomain();
        try {
            user = userService.getUser(LoginInterceptor.getLoginUserId());
        } catch (Throwable e) {
            //not to do
        }
        ProductDetailDomain afterDetail = productExternal.getProductDetail(updateDetail.getProductId());
        Map beforeSkus = Optional.ofNullable(beforeDetail.getSkuInputs()).orElse(new ArrayList<>())
                .stream().collect(Collectors.toMap(sku -> Long.valueOf(sku.getSkuId()), Function.identity()));
        Map afterSkus = Optional.ofNullable(afterDetail.getSkuInputs()).orElse(new ArrayList<>())
                .stream().collect(Collectors.toMap(sku -> sku.getSkuId(), Function.identity()));
        for (SkuDetailDomain afterSku : afterSkus.values()) {
            ProductSkuOperationLog productSkuOperationLog = new ProductSkuOperationLog();
            productSkuOperationLog.setOpPerson(user.getLoginName());
            productSkuOperationLog.setProductName(updateDetail.getName());
            productSkuOperationLog.setProductId(updateDetail.getProductId() + "");
            productSkuOperationLog.setCreateTime(new Date());
            productSkuOperationLog.setSku(afterSku.getName());
            productSkuOperationLog.setBeforeState(beforeDetail.getState());
            productSkuOperationLog.setAfterState(afterDetail.getState());
            SkuDetailDomain beforeSku = beforeSkus.get(afterSku.getSkuId());
            if (beforeSku != null) {
                //更新
                productSkuOperationLog.setLogType(LOG_TYPE_UPDATE);
                productSkuOperationLog.setBeforeRetailPrice(beforeSku.getPrice());
                productSkuOperationLog.setBeforeRetainedProportionOfTheCompany(beforeSku.getRetentionRatio());
                productSkuOperationLog.setBeforeServiceChargeForTalents(beforeSku.getPlatformServiceFee());
                productSkuOperationLog.setBeforeStock(beforeSku.getStock() + "");
                productSkuOperationLog.setBeforeSupplyPrice(beforeSku.getSupplyPrice());
            } else {
                //新增
                productSkuOperationLog.setLogType(LOG_TYPE_ADD);
            }
            productSkuOperationLog.setAfterRetailPrice(afterSku.getPrice());
            productSkuOperationLog.setAfterRetainedProportionOfTheCompany(afterSku.getRetentionRatio());
            productSkuOperationLog.setAfterServiceChargeForTalents(afterSku.getPlatformServiceFee());
            productSkuOperationLog.setAfterStock(afterSku.getStock() + "");
            productSkuOperationLog.setAfterSupplyPrice(afterSku.getSupplyPrice());
            productSkuOperationLogMapper.insert(productSkuOperationLog);
        }
        //删除
        for (SkuDetailDomain beforeSku : beforeSkus.values()) {
            if (!afterSkus.containsKey(beforeSku.getSkuId())) {
                ProductSkuOperationLog productSkuOperationLog = new ProductSkuOperationLog();
                productSkuOperationLog.setOpPerson(user.getLoginName());
                productSkuOperationLog.setProductId(updateDetail.getProductId() + "");
                productSkuOperationLog.setProductName(updateDetail.getName());
                productSkuOperationLog.setCreateTime(new Date());
                productSkuOperationLog.setSku(beforeSku.getName());
                productSkuOperationLog.setBeforeState(beforeDetail.getState());
                productSkuOperationLog.setAfterState(afterDetail.getState());
                productSkuOperationLog.setLogType(LOG_TYPE_DELETE);
                productSkuOperationLog.setBeforeRetailPrice(beforeSku.getPrice());
                productSkuOperationLog.setBeforeRetainedProportionOfTheCompany(beforeSku.getRetentionRatio());
                productSkuOperationLog.setBeforeServiceChargeForTalents(beforeSku.getPlatformServiceFee());
                productSkuOperationLog.setBeforeStock(beforeSku.getStock() + "");
                productSkuOperationLog.setBeforeSupplyPrice(beforeSku.getSupplyPrice());
            }
        }
        return returnValue;
    }
}

可以看出,关键在于调用被代理的方法  Object returnValue = joinPoint.proceed(args);

Spring AOP面向切面编程之自定义日志注解@OperateLog_第1张图片

ItVuer - 免责声明 - 关于我们 - 联系我们

本网站信息来源于互联网,如有侵权请联系:561261067@qq.com

桂ICP备16001015号