SpringBoot整合aop日志管理

該項(xiàng)目源碼地址:https://github.com/ggb2312/JavaNotes/tree/master/springboot-integration-examples (其中包含SpringBoot和其他常用技術(shù)的整合,配套源碼以及筆記?;谧钚碌?SpringBoot2.1+,歡迎各位 Star)

1. 開發(fā)前準(zhǔn)備

1.1 前置知識(shí)

  • java基礎(chǔ)自定義注解、反射
  • Spring aop
  • SpringBoot簡(jiǎn)單基礎(chǔ)知識(shí)即可

1.2 環(huán)境參數(shù)

  • 開發(fā)工具:IDEA
  • 基礎(chǔ)環(huán)境:Maven+JDK8
  • 所用技術(shù):SpringBoot、lombok、mybatisplus、Spring aop
  • SpringBoot版本:2.1.4

1.3 涉及知識(shí)點(diǎn)

  • 自定義注解、 反射
  • spring aop 環(huán)繞通知

2. aop日志實(shí)現(xiàn)

AOP(Aspect Oriented Programming)是一個(gè)大話題,這里不做介紹,直接使用。
實(shí)現(xiàn)效果:用戶在瀏覽器操作web頁(yè)面,對(duì)應(yīng)的操作會(huì)被記錄到數(shù)據(jù)庫(kù)中。
實(shí)現(xiàn)思路:自定義一個(gè)注解,將注解加到某個(gè)方法上,使用aop環(huán)繞通知代理帶有注解的方法,在環(huán)繞前進(jìn)行日志準(zhǔn)備,執(zhí)行完方法后進(jìn)行日志入庫(kù)。
項(xiàng)目結(jié)構(gòu):

項(xiàng)目結(jié)構(gòu)

2.1 log表

CREATE TABLE `log`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `operateor` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `operateType` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `operateDate` datetime(0) NULL DEFAULT NULL,
  `operateResult` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `ip` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 13 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

2.2 pojo

log表對(duì)應(yīng)的實(shí)體類,使用了lombok的@Data注解,也可以使用get、set代替,使用了mybatisplus,所以配置了@TableName等注解,如果使用mybatis或者其他的orm,可以把注解拿掉。

package cn.lastwhisper.springbootaop.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;

@Data
@TableName("log")
public class Log {
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    @TableField("operateor")
    private String operateor;

    @TableField("operateType")
    private String operatetype;

    @TableField("operateDate")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date operatedate;

    @TableField("operatereSult")
    private String operateresult;

    @TableField("ip")
    private String ip;
}

2.3 controller

該Controller用于接收用戶的請(qǐng)求,并對(duì)用戶操作進(jìn)行記錄。

package cn.lastwhisper.springbootaop.controller;
import cn.lastwhisper.springbootaop.core.annotation.LogAnno;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author lastwhisper
 * @desc
 * @email gaojun56@163.com
 */
@RestController
public class UserController {
    /**
     * @desc 這里為了方便直接在controller上進(jìn)行aop日志記錄,也可以放在service上。
     * @author lastwhisper
     * @Param 
     * @return
     */
    @LogAnno(operateType = "添加用戶")
    @RequestMapping(value = "/user/add")
    public void add() {
        System.out.println("向數(shù)據(jù)庫(kù)中添加用戶!!");
    }
}

2.4 mapper

該mapper用于對(duì)log表進(jìn)行操作

package cn.lastwhisper.springbootaop.mapper;

import cn.lastwhisper.springbootaop.pojo.Log;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

/**
 * @desc
 * 
 * @author lastwhisper
 * @email gaojun56@163.com
 */
public interface LogMapper extends BaseMapper<Log> {
}

2.5 core

2.5.1 日志注解

該注解用于標(biāo)識(shí)需要被環(huán)繞通知進(jìn)行日志操作的方法

package cn.lastwhisper.springbootaop.core.annotation;

import org.springframework.core.annotation.Order;

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

/**
 * 日志注解
 *
 * @author lastwhisper
 */
@Target(ElementType.METHOD) // 方法注解
@Retention(RetentionPolicy.RUNTIME) // 運(yùn)行時(shí)可見
public @interface LogAnno {
    String operateType();// 記錄日志的操作類型
}

2.5.2 aop環(huán)繞通知類

對(duì)帶有LogAnno注解的方法進(jìn)行環(huán)繞通知日志記錄。

@Order(3)注解一定要帶上,標(biāo)記支持AspectJ的切面排序

package cn.lastwhisper.springbootaop.core.aop;

import java.lang.reflect.Method;
import java.sql.SQLException;
import java.util.Date;

import cn.lastwhisper.springbootaop.core.annotation.LogAnno;
import cn.lastwhisper.springbootaop.core.common.HttpContextUtil;
import cn.lastwhisper.springbootaop.mapper.LogMapper;
import cn.lastwhisper.springbootaop.pojo.Log;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * AOP實(shí)現(xiàn)日志
 * 
 * @author 最后的輕語(yǔ)_dd43
 * 
 */
@Order(3)
@Component
@Aspect
public class LogAopAspect {
    // 日志mapper,這里省事少寫了service
    @Autowired
    private LogMapper logMapper;

    /**
     * 環(huán)繞通知記錄日志通過注解匹配到需要增加日志功能的方法
     * 
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around("@annotation(cn.lastwhisper.springbootaop.core.annotation.LogAnno)")
    public Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
        // 1.方法執(zhí)行前的處理,相當(dāng)于前置通知
        // 獲取方法簽名
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        // 獲取方法
        Method method = methodSignature.getMethod();
        // 獲取方法上面的注解
        LogAnno logAnno = method.getAnnotation(LogAnno.class);
        // 獲取操作描述的屬性值
        String operateType = logAnno.operateType();
        // 創(chuàng)建一個(gè)日志對(duì)象(準(zhǔn)備記錄日志)
        Log log = new Log();
        log.setOperatetype(operateType);// 操作說明

        // 設(shè)置操作人,從session中獲取,這里簡(jiǎn)化了一下,寫死了。
        log.setOperateor("lastwhisper");
        String ip = HttpContextUtil.getIpAddress();
        log.setIp(ip);
        Object result = null;
        try {
            // 讓代理方法執(zhí)行
            result = pjp.proceed();
            // 2.相當(dāng)于后置通知(方法成功執(zhí)行之后走這里)
            log.setOperateresult("正常");// 設(shè)置操作結(jié)果
        } catch (SQLException e) {
            // 3.相當(dāng)于異常通知部分
            log.setOperateresult("失敗");// 設(shè)置操作結(jié)果
        } finally {
            // 4.相當(dāng)于最終通知
            log.setOperatedate(new Date());// 設(shè)置操作日期
            logMapper.insert(log);// 添加日志記錄
        }
        return result;
    }
    
}

2.5.3 common

用于獲取用戶的ip

package cn.lastwhisper.springbootaop.core.common;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @desc
 * 
 * @author lastwhisper
 * @email gaojun56@163.com
 */
public class HttpContextUtil {
    public static HttpServletRequest getRequest() {
        return  ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
    }

    /**
     * 獲取IP地址的方法
     *
     * @param request 傳一個(gè)request對(duì)象下來(lái)
     * @return
     */
    public static String getIpAddress() {
        HttpServletRequest request = getRequest();
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}

2.6 最終配置

配置application.properties文件

spring.application.name = lastwhisper-aoplog
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/wxlogin?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=root

配置springboot啟動(dòng)類SpringbootaopApplication

package cn.lastwhisper.springbootaop;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@MapperScan("cn.lastwhisper.springbootaop.mapper") //設(shè)置mapper接口的掃描包
@SpringBootApplication
public class SpringbootaopApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootaopApplication.class, args);
    }

}

至此一個(gè)完整的SpringBoot AOP日志系統(tǒng)基本成型。

3. 測(cè)試

啟動(dòng)SpringbootaopApplication的main方法。訪問 http://localhost:8080/user/add

會(huì)在idea的控制臺(tái)看到 ``

console

然后再看一下數(shù)據(jù)庫(kù),保存了日志信息。


aop 日志

如果是springmvc項(xiàng)目沒有生效,應(yīng)該是自定義aop與事務(wù)aop順序問題,需要在配置文件中配置order="200"。如果配置文件配置order無(wú)效,建議不要使用配置文件事務(wù),使用注解事務(wù)。
springmvc項(xiàng)目配置示例

<!-- 開啟注解AOP -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
    <!-- 注解方式配置事物,為了配合自定義注解 -->
<tx:annotation-driven
    transaction-manager="transactionManager" proxy-target-class="true"
        order="200" />
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容