您好,登錄后才能下訂單哦!
Spring如利用aop操作日志功?相信很多沒有經(jīng)驗(yàn)的人對(duì)此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。
1. 在pom中添加所需依賴
創(chuàng)建一個(gè)springboot工程,添加所需要的依賴,持久化用的是mybatis
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--springboot aop依賴--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <!--mybatis--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.3</version> </dependency> <!--mysql連接--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.19</version> <scope>runtime</scope> </dependency> <!--lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>
2. 創(chuàng)建日志實(shí)體類
import lombok.Data; import java.io.Serializable; @Data public class AdminLog implements Serializable { private static final long serialVersionUID = -291495801959706565L; private Integer id; //日志記錄id private Integer userId;//操作人id private String userName;//操作人name private String loginip;//登錄ip private int type; private String url; private String operation; private String createtime; private String remark; }
3. 自定義log注解
import java.lang.annotation.*; /** * 自定義日志注解 */ @Target(ElementType.METHOD) //注解防止位置 @Retention(RetentionPolicy.RUNTIME)//運(yùn)行時(shí)可見 @Documented //生成文檔 public @interface MyLog { String operation() default ""; int type(); }
4. 創(chuàng)建aop切面處理類
import cn.***.springaopdemo.anno.MyLog; import cn.***.springaopdemo.dao.MyLogMapper; import cn.***.springaopdemo.pojo.Admin; import cn.***.springaopdemo.pojo.AdminLog; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; 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; /** * 切面處理類 */ @Aspect @Component public class SysLogAspect { /** * 使用log4j2把一些信息打印在控制臺(tái)上面 */ private static final Logger log = LogManager.getLogger(SysLogAspect.class); @Autowired private MyLogMapper myLogMapper; //定義切點(diǎn) @Pointcut //在注解的位置切入代碼 @Pointcut("@annotation(cn.***.springaopdemo.anno.MyLog)") public void logPointCut() { } //切面 配置為前置通知 @Before("logPointCut()") public void saveOperation(JoinPoint joinPoint) { log.info("---------------接口日志記錄---------------"); //創(chuàng)建一個(gè)日志對(duì)象 AdminLog adminLog = new AdminLog(); //獲取切面織處入點(diǎn)的方法 MethodSignature signature = (MethodSignature) joinPoint.getSignature(); //獲取切入點(diǎn)所在的方法 Method method = signature.getMethod(); //獲取操作日志的屬性值 MyLog myLog = method.getAnnotation(MyLog.class); if (myLog != null) { //操作事件 String operation = myLog.operation(); adminLog.setOperation(operation); //日志類型 int type = myLog.type(); adminLog.setType(type); log.info("operation=" + operation + ",type=" + type); } //獲取url HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); String requestURL = request.getRequestURI().toString(); adminLog.setUrl(requestURL); //獲取客戶端ip String ip = request.getRemoteAddr(); adminLog.setLoginip(ip); //獲取操作人賬號(hào)、姓名(需要提前將用戶信息保存到Session) Admin admin = (Admin) request.getSession().getAttribute("admin"); if (admin != null) { Integer id = admin.getId(); String name = admin.getName(); adminLog.setUserId(id); adminLog.setUserName(name); } log.info("url=" + requestURL + ",ip=" + ip); //調(diào)用service保存Operation實(shí)體類到數(shù)據(jù)庫 //可以在這設(shè)置id,因?yàn)槭菧y(cè)試,這里就使用的是數(shù)據(jù)庫的自增id myLogMapper.insertLog(adminLog); } }
5. mapper層把日志數(shù)據(jù)存儲(chǔ)到mysql數(shù)據(jù)庫中
mapper接口
import cn.***.springaopdemo.pojo.AdminLog; import java.util.List; public interface MyLogMapper { void insertLog(AdminLog adminLog); }
mapper.xml文件
<?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="cn.***.springaopdemo.dao.MyLogMapper"> <insert id="insertLog" parameterType="cn.***.springaopdemo.pojo.AdminLog"> INSERT INTO admin_log (user_id,user_name,loginip,type,url,operation,createtime,remark) VALUES (#{userId},#{userName},#{loginip},#{type},#{url},#{operation},now(),#{remark}) </insert> </mapper>
6. 測(cè)試
先直接登錄用戶,因?yàn)槭菧y(cè)試,直接從數(shù)據(jù)庫中獲取后登錄,把a(bǔ)dmin存儲(chǔ)到session中
import cn.***.springaopdemo.pojo.Admin; import cn.***.springaopdemo.service.IAdminService; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import java.util.List; @RestController @RequestMapping("/admin") public class AdminController { private static final Logger log = LogManager.getLogger(AdminController.class); //中間service層可以省略,直接通過mapper接口操作數(shù)據(jù)即可 @Autowired private IAdminService adminService; @RequestMapping("/login") public Admin login(HttpServletRequest request) { List<Admin> adminList = adminService.findAllAdmin(); Admin admin = adminList.get(0); request.getSession().setAttribute("admin",admin ); return admin; } }
在瀏覽器中輸入localhost:8080/admin/login,可以看到登錄的admin
進(jìn)行插入和查詢操作,插入數(shù)據(jù)直接通過后臺(tái)提供
import cn.***.springaopdemo.anno.MyLog; import cn.***.springaopdemo.pojo.Type; import cn.***.springaopdemo.service.ITypeService; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; @RestController @RequestMapping("/type") public class TypeController { private static final Logger log = LogManager.getLogger(TypeController.class); @Autowired private ITypeService typeService; @MyLog(operation = "增加書籍類型", type = 2) @RequestMapping("/add") public void insertType() { List<Type> typeList = new ArrayList<>(); Type type = new Type(); type.setName("自然科學(xué)"); typeList.add(type); typeService.addTypeList(typeList); log.info("添加書籍類型" + type.getName()); } @MyLog(operation = "查詢所有書籍類型", type = 1) @RequestMapping("/findAll") public List<Type> findAllType() { List<Type> typeList = typeService.findAllType(); log.info("查詢所有書籍類型"); return typeList; } }
在瀏覽器中輸入localhost:8080/type/add,后臺(tái)日志打印記錄
再輸入查詢請(qǐng)求localhost:8080/type/findAll,獲得查詢出的分類
查看數(shù)據(jù)庫是否添加成功
看完上述內(nèi)容,你們掌握Spring如利用aop操作日志功的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。