AOP+自定义注解实现日志管理

需求 : 在Controller获得Service层的方法上加上自定义日志注解,实现日志管理。


一.对应的数据库(日志) :

CREATE TABLE `log` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `ope_method` varchar(255) DEFAULT NULL COMMENT '方法名',
  `ope_desc` varchar(255) DEFAULT NULL COMMENT '描述',
  `ope_date` datetime DEFAULT NULL COMMENT '日志记录时间',
  `ope_ip` varchar(255) DEFAULT NULL COMMENT 'IP',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

二.创建Log(日志)实体类 :

package com.zzx.model;

import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;

public class Log {
    private Integer id;

    private String opeMethod;

    private String opeDesc;

    @DateTimeFormat(pattern = "yyyy-mm-dd")
    private Date opeDate;

    private String opeIp;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getOpeMethod() {
        return opeMethod;
    }

    public void setOpeMethod(String opeMethod) {
        this.opeMethod = opeMethod == null ? null : opeMethod.trim();
    }

    public String getOpeDesc() {
        return opeDesc;
    }

    public void setOpeDesc(String opeDesc) {
        this.opeDesc = opeDesc == null ? null : opeDesc.trim();
    }

    public Date getOpeDate() {
        return opeDate;
    }

    public void setOpeDate(Date opeDate) {
        this.opeDate = opeDate;
    }

    public String getOpeIp() {
        return opeIp;
    }

    public void setOpeIp(String opeIp) {
        this.opeIp = opeIp == null ? null : opeIp.trim();
    }

    @Override
    public String toString() {
        return "Log{" +
                "id=" + id +
                ", opeMethod='" + opeMethod + '\'' +
                ", opeDesc='" + opeDesc + '\'' +
                ", opeDate=" + opeDate +
                ", opeIp='" + opeIp + '\'' +
                '}';
    }
}

三.在Mapper创建接口类 :

package com.zzx.mapper;

import com.zzx.model.Log;

public interface LogMapper {
	//添加日志
    int insert(Log record);
}

四.在映射文件下写添加日志数据SQL :

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.zzx.mapper.LogMapper" >
  <resultMap id="BaseResultMap" type="com.zzx.model.Log" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="ope_method" property="opeMethod" jdbcType="VARCHAR" />
    <result column="ope_desc" property="opeDesc" jdbcType="VARCHAR" />
    <result column="ope_date" property="opeDate" jdbcType="TIMESTAMP" />
    <result column="ope_ip" property="opeIp" jdbcType="VARCHAR" />
  </resultMap>
 	<sql id="Base_Column_List" >
    	id, ope_method, ope_desc, ope_date, ope_ip
  	</sql>
 <insert id="insert" parameterType="com.zzx.model.Log" >
    insert into log (id, ope_method, ope_desc, ope_date, ope_ip)
    values
     (#{id,jdbcType=INTEGER}, #{opeMethod,jdbcType=VARCHAR}, {opeDesc,jdbcType=VARCHAR}, 
      #{opeDate,jdbcType=TIMESTAMP}, #{opeIp,jdbcType=VARCHAR})
  </insert>

五.创建Service接口 :

package com.zzx.service;

import com.zzx.model.Log;

/**
 * @auther ZhengZiXuan
 * @date 2021/3/17 20:07
 * @desc
 */
public interface LogService {
    int insert(Log record);
}

六.创建ServiceImpl实现类 :

package com.zzx.service.impl;

import com.zzx.mapper.LogMapper;
import com.zzx.model.Log;
import com.zzx.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @auther ZhengZiXuan
 * @date 2021/3/17 20:08
 * @desc
 */
@Service
public class LogServiceImpl implements LogService {
    @Autowired
    private LogMapper logMapper;
    
    @Override
    public int insert(Log record) {
        return logMapper.insert(record);
    }
}

七.创建自定义注解类(重点) :

package com.zzx.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
 * @auther ZhengZiXuan
 * @date 2021/3/17 19:48
 * @desc Aop + 自定义注解实现日志管理
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyLog {
    String value() default ""; //日志描述
    String desc() default "";  //日志描述
}

八.创建切面类(重点) :

package com.zzx.aspect;

import com.zzx.annotation.MyLog;
import com.zzx.model.Log;
import com.zzx.service.LogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @auther ZhengZiXuan
 * @date 2021/3/17 19:52
 * @desc 切面类
 */
@Component
@Aspect
public class LogAspect {
    @Autowired
    private LogService logService;

    //切入点是:自定义注解加在哪个方法上,哪个方法就是切入点
    @Before("@annotation(com.zzx.annotation.MyLog)")
    public void Log(JoinPoint joinPoint){
        //1.获取目标方法名
        String MethodName = joinPoint.getSignature().getName();

        //2.获得目标方法上的注解的值
        Object target = joinPoint.getTarget();  //目标方法所在类的对象

        //获得目标类的所有方法
        String desc = null;
        Method[] declaredMethods = target.getClass().getDeclaredMethods();
        for (Method declaredMethod : declaredMethods) {
            if (declaredMethod.getName().equals(MethodName)){
                MyLog annotation = declaredMethod.getAnnotation(MyLog.class);
                desc = annotation.value();
            }
        }

        //3.时间
        Date date = new Date();

        //4.ip
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = request.getRemoteHost();
        System.out.println(">>>>>>>>>>>>>>"+MethodName);
        System.out.println(">>>>>>>>>>>>>>"+desc);
        System.out.println(">>>>>>>>>>>>>>"+date);
        System.out.println(">>>>>>>>>>>>>>"+ip);
        Log log = new Log();
        log.setOpeDate(date);
        log.setOpeDesc(desc);
        log.setOpeIp(ip);
        log.setOpeMethod(MethodName);
        logService.insert(log);
    }
}

九.开启AOP注解功能 :

自定义注解加在Controller层的方法上,就需要在springmvc.xml中配置aop注解
自定义注解加在Service层的方法上,就需要在application.xml中配置aop注解
开启的注解功能的代码如下 :

<aop:aspectj-autoproxy/>

十.使用注解

在Controller层或者Service层加上日志注解即可 。
在这里插入图片描述
添加"AOP+自定义注解实现日志管理"以后的效果 :
在这里插入图片描述

  • 3
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小郑要做干饭人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值