SpringBoot整合aop日誌管理

該項目源碼地址:https://github.com/ggb2312/springboot-integration-examples (其中包含SpringBoot和其他常用技術的整合,配套源碼以及筆記。基於最新的 SpringBoot2.1+,歡迎各位 Star)

1. 開發前準備

1.1 前置知識

  • java基礎自定義註解、反射
  • Spring aop
  • SpringBoot簡單基礎知識即可

1.2 環境參數

  • 開發工具:IDEA
  • 基礎環境:Maven+JDK8
  • 所用技術:SpringBoot、lombok、mybatisplus、Spring aop
  • SpringBoot版本:2.1.4

1.3 涉及知識點

  • 自定義註解、 反射
  • spring aop 環繞通知

2. aop日誌實現

AOP(Aspect Oriented Programming)是一個大話題,這裏不做介紹,直接使用。
**實現效果:**用戶在瀏覽器操作web頁面,對應的操作會被記錄到數據庫中。
**實現思路:**自定義一個註解,將註解加到某個方法上,使用aop環繞通知代理帶有註解的方法,在環繞前進行日誌準備,執行完方法後進行日誌入庫。
項目結構:
項目結構

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表對應的實體類,使用了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用於接收用戶的請求,並對用戶操作進行記錄。

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 [email protected]
 */
@RestController
public class UserController {
    /**
     * @desc 這裏爲了方便直接在controller上進行aop日誌記錄,也可以放在service上。
     * @author lastwhisper
     * @Param 
     * @return
     */
    @LogAnno(operateType = "添加用戶")
    @RequestMapping(value = "/user/add")
    public void add() {
        System.out.println("向數據庫中添加用戶!!");
    }
}

2.4 mapper

該mapper用於對log表進行操作

package cn.lastwhisper.springbootaop.mapper;

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

/**
 * @desc
 * 
 * @author lastwhisper
 * @email [email protected]
 */
public interface LogMapper extends BaseMapper<Log> {
}

2.5 core

2.5.1 日誌註解

該註解用於標識需要被環繞通知進行日誌操作的方法

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) // 運行時可見
public @interface LogAnno {
    String operateType();// 記錄日誌的操作類型
}

2.5.2 aop環繞通知類

對帶有LogAnno註解的方法進行環繞通知日誌記錄。

@Order(3)註解一定要帶上,標記支持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實現日誌
 * 
 * @author 最後的輕語_dd43
 * 
 */
@Order(3)
@Component
@Aspect
public class LogAopAspect {
	// 日誌mapper,這裏省事少寫了service
	@Autowired
	private LogMapper logMapper;

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

		// 設置操作人,從session中獲取,這裏簡化了一下,寫死了。
		log.setOperateor("lastwhisper");
		String ip = HttpContextUtil.getIpAddress();
		log.setIp(ip);
		Object result = null;
		try {
			// 讓代理方法執行
			result = pjp.proceed();
			// 2.相當於後置通知(方法成功執行之後走這裏)
			log.setOperateresult("正常");// 設置操作結果
		} catch (SQLException e) {
			// 3.相當於異常通知部分
			log.setOperateresult("失敗");// 設置操作結果
		} finally {
			// 4.相當於最終通知
			log.setOperatedate(new Date());// 設置操作日期
			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 [email protected]
 */
public class HttpContextUtil {
    public static HttpServletRequest getRequest() {
        return  ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
    }

    /**
     * 獲取IP地址的方法
     *
     * @param request 傳一個request對象下來
     * @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啓動類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") //設置mapper接口的掃描包
@SpringBootApplication
public class SpringbootaopApplication {

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

}

至此一個完整的SpringBoot AOP日誌系統基本成型。

3. 測試

啓動SpringbootaopApplication的main方法。訪問 http://localhost:8080/user/add

會在idea的控制檯看到 ``

console

然後再看一下數據庫,保存了日誌信息。
aop 日誌

如果是springmvc項目沒有生效,應該是自定義aop與事務aop順序問題,需要在配置文件中配置order="200"。如果配置文件配置order無效,建議不要使用配置文件事務,使用註解事務。
springmvc項目配置示例

<!-- 開啓註解AOP -->
	<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
	<!-- 註解方式配置事物,爲了配合自定義註解 -->
<tx:annotation-driven
	transaction-manager="transactionManager" proxy-target-class="true"
		order="200" />
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章