使用aop动态代理实现记录用户操作

  1. 引入依赖
	<!--面向切面-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
  1. LogAspect类
@Configuration
@Aspect
@Slf4j
public class LogAspect {

    @Autowired
    private LogService logService;

    @Resource
    HttpSession session;

    //记录用户的日志
    @Around("@annotation(com.xiaozhi.annotation.AddLog)")
    public Object addLog(ProceedingJoinPoint proceedingJoinPoint){
        log.info("--环绕通知");
        //谁 时间 操作 是否成功
        User user = (User) session.getAttribute("user");
        //获取方法
        MethodSignature methodSignature= (MethodSignature) proceedingJoinPoint.getSignature();
        Method method = methodSignature.getMethod();
        //获取方法上的注解
        AddLog addLog = method.getAnnotation(AddLog.class);
        //获取注解属性的值
        String value = addLog.value();
        //获取方法名 操作的哪个方法
        String name = proceedingJoinPoint.getSignature().getName();
        //放行
        Object methodResult=null;
        try{
           methodResult = proceedingJoinPoint.proceed();
           String message = "success";
           Log logs = new Log(UUID.randomUUID().toString(), user.getUsername(), new Date(),value + "(" + name + ")", message);
           logService.insert(logs);
           log.info("日志入库"+logs);
        }catch (Throwable throwable){
            throwable.printStackTrace();
            String message = "error";
        }
        return methodResult;
    }
}

  1. AddLog annotation
@Target(ElementType.METHOD)  //使用在方法上
@Retention(RetentionPolicy.RUNTIME)   //运行时生效
public @interface AddLog {
    String value();

    String name() default "";
}

  1. 根据注解使用代理
	@AddLog(value = "修改用户")
    @Override
    public User update(User user) {
        this.userDao.update(user);
        return this.queryById(user.getId());
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值