---
title: "Spring AOP 完成日志记录"
author: "paynexss"
date: "2017-04-21T11:03:25Z"
tags: ["AOP"]
categories: ["编程语言"]
slug: "spring-aop"
draft: false
lastmod: "2017-04-21T11:03:25Z"
id: 2370612
url: "https://paynexss.iteye.com/blog/2370612"
---

**1、技术目标**

 

 

- 掌握Spring AOP基本用法
- 使用Spring AOP完成日志记录功能

 

 

**提示：本文所用项目为"影片管理"，参看**

[**http://hotstrong.iteye.com/blog/1160153**](http://hotstrong.iteye.com/blog/1160153)

**本文基于"影片管理"项目进行了日志记录功能扩充**

 

**注意：本文所实现的项目(MyEclipse工程)已提供下载，数据库**

**脚本可参看[《MyBatis 1章 入门(使用MyBatis完成CRUD)》](http://hotstrong.iteye.com/blog/1087867)**

 

 

**2、什么是AOP**

 

AOP是Aspect Oriented Programming的缩写，意思是面向方面编程，AOP实际是GoF设计模式的延续

 

**注意：关于AOP的详细介绍不是本文重点**

 

 

**3、关于Spring AOP的一些术语**

 

- **切面（Aspect）**：在Spring AOP中，切面可以使用通用类或者在普通类中以@Aspect 注解（@AspectJ风格）来实现

<!--THE END-->

- **连接点（Joinpoint）**：在Spring AOP中一个连接点代表一个方法的执行

<!--THE END-->

- **通知（Advice）**：在切面的某个特定的连接点（Joinpoint）上执行的动作。通知有各种类型，其中包括"around"、"before”和"after"等通知。许多AOP框架，包括Spring，都是以拦截器做通知模型， 并维护一个以连接点为中心的拦截器链

<!--THE END-->

- **切入点（Pointcut）**：定义出一个或一组方法，当执行这些方法时可产生通知，Spring缺省使用AspectJ切入点语法。

 

 

**4、通知类型**

 

- **前置通知（@Before）**：在某连接点（join point）之前执行的通知，但这个通知不能阻止连接点前的执行（除非它抛出一个异常）

<!--THE END-->

- **返回后通知（@AfterReturning）**：在某连接点（join point）正常完成后执行的通知：例如，一个方法没有抛出任何异常，正常返回

<!--THE END-->

- **抛出异常后通知（@AfterThrowing）**：方法抛出异常退出时执行的通知

<!--THE END-->

- **后通知（@After）**：当某连接点退出的时候执行的通知（不论是正常返回还是异常退出）

<!--THE END-->

- **环绕通知（@Around）**：包围一个连接点（join point）的通知，如方法调用。这是最强大的一种通知类型，环绕通知可以在方法调用前后完成自定义的行为，它也会选择是否继续执行连接点或直接返回它们自己的返回值或抛出异常来结束执行

 

 

**5、@AspectJ风格的AOP配置**

 

Spring AOP配置有两种风格：

 

- XML风格 = 采用声明形式实现Spring AOP
- AspectJ风格 = 采用注解形式实现Spring AOP

 

 

**注意：本文采用AspectJ风格**

 

**6、使用准备**

闲话少说，下面开始日志记录的准备工作

 

**6.1）创建日志记录表(MySQL)，**

 

 

Sql代码  [![收藏代码](http://hotstrong.iteye.com/images/icon_star.png)]()

1. CREATE TABLE \`t\_log\` (
2. \`id\` bigint(20) unsigned NOT NULL AUTO\_INCREMENT,
3. \`userid\` bigint(20) unsigned NOT NULL,
4. \`createdate\` timestamp NOT NULL DEFAULT CURRENT\_TIMESTAMP ON UPDATE CURRENT\_TIMESTAMP COMMENT '创建日期',
5. \`content\` varchar(8000) NOT NULL DEFAULT '' COMMENT '日志内容',
6. \`operation\` varchar(250) NOT NULL DEFAULT '' COMMENT '用户所做的操作',
7. PRIMARY KEY (\`id\`)
8. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

 

 

**6.2）在经过了Spring Security的权限验证后，可以从Security中获取到**

**登录管理员的帐号，而日志记录表t\_log中存储的是管理员id，所以需要通**

**过管理员的帐号查询出管理员id，创建管理员POJO、Mapper、Service，**

**代码及配置如下：**

 

**管理员POJO类：**

 

 

Java代码  [![收藏代码](http://hotstrong.iteye.com/images/icon_star.png)]()

01. package com.xxx.pojo;
02. public class Admin extends BaseDomain {
03. private String nickname;//管理员帐号
04. private String passwd;//管理员密码
05. private String phoneno;//联系电话
06. public String getNickname() {
07. return nickname;
08. }
09. public void setNickname(String nickname) {
10. this.nickname = nickname;
11. }
12. public String getPasswd() {
13. return passwd;
14. }
15. public void setPasswd(String passwd) {
16. this.passwd = passwd;
17. }
18. public String getPhoneno() {
19. return phoneno;
20. }
21. public void setPhoneno(String phoneno) {
22. this.phoneno = phoneno;
23. }
24. }

 

 

 

**管理员Mapper接口与XML配置文件：**

 

 

Java代码  [![收藏代码](http://hotstrong.iteye.com/images/icon_star.png)]()

01. package com.xxx.dao;
02. import com.xxx.pojo.Admin;
03. /\**
04. * 管理员Mapper接口
05. \*/
06. public interface AdminMapper {
07. /\**
08. * 获取指定帐号名的管理员
09. \*/
10. public Admin findAdminByNickname(String userName);
11. }

 

 

 

Xml代码  [![收藏代码](http://hotstrong.iteye.com/images/icon_star.png)]()

1. &lt;?xml version="1.0" encoding="UTF-8"?&gt;
2. &lt;!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd"&gt;
4. &lt;mapper namespace="com.xxx.dao.AdminMapper"&gt;
5. &lt;!-- 通过账号名称查询管理员 --&gt;
6. &lt;select id="findAdminByNickname" parameterType="string" resultType="Admin"&gt;
7. select * from t\_admin where nickname=#{userName}
8. &lt;/select&gt;
9. &lt;/mapper&gt;

 

 

 

**管理员Service接口与实现类：**

 

 

Java代码  [![收藏代码](http://hotstrong.iteye.com/images/icon_star.png)]()

01. package com.xxx.service;
02. import com.xxx.pojo.Admin;
03. /\**
04. * 管理员信息业务逻辑接口
05. \*/
06. public interface AdminService {
07. /\**
08. * 获取指定帐号名的管理员
09. \*/
10. public Admin findAdminByNickname(String userName);
11. }

 

 

Java代码  [![收藏代码](http://hotstrong.iteye.com/images/icon_star.png)]()

01. package com.xxx.service;
02. import org.springframework.beans.factory.annotation.Autowired;
03. import com.xxx.dao.AdminMapper;
04. import com.xxx.pojo.Admin;
05. public class AdminServiceImpl implements AdminService {
06. @Autowired
07. private AdminMapper adminMapper;//Mapper接口
08. public Admin findAdminByNickname(String userName) {
09. return adminMapper.findAdminByNickname(userName);
10. }
11. }

 

 

**6.3）创建日志记录POJO、Mapper、Service，代码及配置如下：**

 

**日志记录POJO类：**

 

 

Java代码  [![收藏代码](http://hotstrong.iteye.com/images/icon_star.png)]()

01. package com.xxx.pojo;
02. import java.io.Serializable;
03. import java.util.Date;
04. /\**
05. * 日志记录POJO
06. \*/
07. public class Log extends BaseDomain implements Serializable{
08. private static final long serialVersionUID = 1024792477652984770L;
09. private Long userid;//管理员id
10. private Date createdate;//日期
11. private String content;//日志内容
12. private String operation;//操作(主要是"添加"、"修改"、"删除")
13. //getter、setter，此处省略N字(你懂的)
14. }

 

 

 

**日志记录Mapper接口与XML配置文件：**

 

 

Java代码  [![收藏代码](http://hotstrong.iteye.com/images/icon_star.png)]()

1. package com.xxx.dao;
2. import com.xxx.pojo.Log;
3. /\**
4. * 日志记录Mapper
5. \*/
6. public interface LogMapper {
7. public void insert(Log log);//添加日志记录
8. }

 

 

 

Xml代码  [![收藏代码](http://hotstrong.iteye.com/images/icon_star.png)]()

01. &lt;?xml version="1.0" encoding="UTF-8"?&gt;
02. &lt;!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
03. "http://mybatis.org/dtd/mybatis-3-mapper.dtd"&gt;
04. &lt;mapper namespace="com.xxx.dao.LogMapper"&gt;
05. &lt;!-- 添加日志记录 --&gt;
06. &lt;insert id="insert" parameterType="Log"&gt;
07. INSERT INTO t\_log(userid,createdate,operation,content)
08. VALUES(#{userid},NOW(),#{operation},#{content});
09. &lt;/insert&gt;
10. &lt;/mapper&gt;

 

 

**日志记录Service接口与实现类：**

 

 

Java代码  [![收藏代码](http://hotstrong.iteye.com/images/icon_star.png)]()

01. package com.xxx.service;
02. import org.springframework.transaction.annotation.Transactional;
03. import com.xxx.pojo.Log;
04. /\**
05. * 日志记录业务逻辑接口
06. \*/
07. public interface LogService {
08. /\**
09. * 日志记录
10. * @param log
11. \*/
12. @Transactional
13. public void log(Log log);
14. /\**
15. * 获取登录管理员ID
16. \*/
17. public Long loginUserId();
18. }

 

 

Java代码  [![收藏代码](http://hotstrong.iteye.com/images/icon_star.png)]()

01. package com.xxx.service;
02. import org.springframework.beans.factory.annotation.Autowired;
03. import org.springframework.security.core.context.SecurityContextHolder;
04. import org.springframework.security.core.userdetails.UserDetails;
05. import com.xxx.dao.LogMapper;
06. import com.xxx.pojo.Admin;
07. import com.xxx.pojo.Log;
08. /\**
09. * 日志记录业务逻辑接口实现类
10. * @author HotStrong
11. \*/
12. public class LogServiceImpl implements LogService{
13. @Autowired
14. private AdminService adminService;
15. @Autowired
16. private LogMapper logMapper;
17. public void log(Log log) {
18. logMapper.insert(log);
19. }
20. /\**
21. * 获取登录管理员ID
22. \*
23. * @return
24. \*/
25. public Long loginUserId() {
26. if(SecurityContextHolder.getContext() == null){
27. return null;
28. }
29. if(SecurityContextHolder.getContext().getAuthentication() == null){
30. return null;
31. }
32. UserDetails userDetails = (UserDetails) SecurityContextHolder
33. .getContext().getAuthentication().getPrincipal();
34. if(userDetails == null){
35. return null;
36. }
37. //获取登录管理员帐号名
38. String userName = userDetails.getUsername();
39. if(userName == null || userName.equals("")){
40. return null;
41. }
42. // 根据管理员帐号名获取帐号ID
43. Admin admin = this.adminService.findAdminByNickname(userName);
44. if(admin == null){
45. return null;
46. }
47. return admin.getId();
48. }
49. }

 

 

 

**7、在MyBatis配置文件mybatis-config.xml中配置POJO，如下：**

 

 

Xml代码  [![收藏代码](http://hotstrong.iteye.com/images/icon_star.png)]()

01. &lt;?xml version="1.0" encoding="UTF-8"?&gt;
02. &lt;!DOCTYPE configuration
03. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
04. "http://mybatis.org/dtd/mybatis-3-config.dtd"&gt;
05. &lt;configuration&gt;
06. &lt;settings&gt;
07. &lt;!-- changes from the defaults --&gt;
08. &lt;setting name="lazyLoadingEnabled" value="false" /&gt;
09. &lt;/settings&gt;
10. &lt;typeAliases&gt;
11. &lt;typeAlias alias="Film" type="com.xxx.pojo.Film"/&gt;
12. &lt;typeAlias alias="Admin" type="com.xxx.pojo.Admin"/&gt;
13. &lt;typeAlias alias="Log" type="com.xxx.pojo.Log"/&gt;
14. &lt;/typeAliases&gt;
15. &lt;/configuration&gt;

 

 

 

 

**8、创建aop包，在aop包下创建切面类LogAspect**

 

 

Java代码  [![收藏代码](http://hotstrong.iteye.com/images/icon_star.png)]()

001. package com.xxx.aop;
002. import java.lang.reflect.Method;
003. import java.util.Date;
004. import org.aspectj.lang.JoinPoint;
005. import org.aspectj.lang.ProceedingJoinPoint;
006. import org.aspectj.lang.annotation.AfterReturning;
007. import org.aspectj.lang.annotation.Around;
008. import org.aspectj.lang.annotation.Aspect;
009. import org.aspectj.lang.annotation.Pointcut;
010. import org.springframework.beans.factory.annotation.Autowired;
011. import com.xxx.pojo.Film;
012. import com.xxx.pojo.Log;
013. import com.xxx.service.FilmService;
014. import com.xxx.service.LogService;
015. /\**
016. * 日志记录，添加、删除、修改方法AOP
017. * @author HotStrong
018. \*
019. \*/
020. @Aspect
021. public class LogAspect {
022. @Autowired
023. private LogService logService;//日志记录Service
024. @Autowired
025. private FilmService filmService;//影片Service
026. /\**
027. * 添加业务逻辑方法切入点
028. \*/
029. @Pointcut("execution(* com.xxx.service.\*.insert\*(..))")
030. public void insertServiceCall() { }
031. /\**
032. * 修改业务逻辑方法切入点
033. \*/
034. @Pointcut("execution(* com.xxx.service.\*.update\*(..))")
035. public void updateServiceCall() { }
036. /\**
037. * 删除影片业务逻辑方法切入点
038. \*/
039. @Pointcut("execution(* com.xxx.service.FilmService.deleteFilm(..))")
040. public void deleteFilmCall() { }
041. /\**
042. * 管理员添加操作日志(后置通知)
043. * @param joinPoint
044. * @param rtv
045. * @throws Throwable
046. \*/
047. @AfterReturning(value="insertServiceCall()", argNames="rtv", returning="rtv")
048. public void insertServiceCallCalls(JoinPoint joinPoint, Object rtv) throws Throwable{
049. //获取登录管理员id
050. Long adminUserId = logService.loginUserId();
051. if(adminUserId == null){//没有管理员登录
052. return;
053. }
054. //判断参数
055. if(joinPoint.getArgs() == null){//没有参数
056. return;
057. }
058. //获取方法名
059. String methodName = joinPoint.getSignature().getName();
060. //获取操作内容
061. String opContent = adminOptionContent(joinPoint.getArgs(), methodName);
062. //创建日志对象
063. Log log = new Log();
064. log.setUserid(logService.loginUserId());//设置管理员id
065. log.setCreatedate(new Date());//操作时间
066. log.setContent(opContent);//操作内容
067. log.setOperation("添加");//操作
068. logService.log(log);//添加日志
069. }
070. /\**
071. * 管理员修改操作日志(后置通知)
072. * @param joinPoint
073. * @param rtv
074. * @throws Throwable
075. \*/
076. @AfterReturning(value="updateServiceCall()", argNames="rtv", returning="rtv")
077. public void updateServiceCallCalls(JoinPoint joinPoint, Object rtv) throws Throwable{
078. //获取登录管理员id
079. Long adminUserId = logService.loginUserId();
080. if(adminUserId == null){//没有管理员登录
081. return;
082. }
083. //判断参数
084. if(joinPoint.getArgs() == null){//没有参数
085. return;
086. }
087. //获取方法名
088. String methodName = joinPoint.getSignature().getName();
089. //获取操作内容
090. String opContent = adminOptionContent(joinPoint.getArgs(), methodName);
091. //创建日志对象
092. Log log = new Log();
093. log.setUserid(logService.loginUserId());//设置管理员id
094. log.setCreatedate(new Date());//操作时间
095. log.setContent(opContent);//操作内容
096. log.setOperation("修改");//操作
097. logService.log(log);//添加日志
098. }
099. /\**
100. * 管理员删除影片操作(环绕通知)，使用环绕通知的目的是
101. * 在影片被删除前可以先查询出影片信息用于日志记录
102. * @param joinPoint
103. * @param rtv
104. * @throws Throwable
105. \*/
106. @Around(value="deleteFilmCall()", argNames="rtv")
107. public Object deleteFilmCallCalls(ProceedingJoinPoint pjp) throws Throwable {
108. Object result = null;
109. //环绕通知处理方法
110. try {
111. //获取方法参数(被删除的影片id)
112. Integer id = (Integer)pjp.getArgs()\[0];
113. Film obj = null;//影片对象
114. if(id != null){
115. //删除前先查询出影片对象
116. obj = filmService.getFilmById(id);
117. }
118. //执行删除影片操作
119. result = pjp.proceed();
120. if(obj != null){
121. //创建日志对象
122. Log log = new Log();
123. log.setUserid(logService.loginUserId());//用户编号
124. log.setCreatedate(new Date());//操作时间
125. StringBuffer msg = new StringBuffer("影片名 : ");
126. msg.append(obj.getFname());
127. log.setContent(msg.toString());//操作内容
128. log.setOperation("删除");//操作
129. logService.log(log);//添加日志
130. }
131. }
132. catch(Exception ex) {
133. ex.printStackTrace();
134. }
135. return result;
136. }
137. /\**
138. * 使用Java反射来获取被拦截方法(insert、update)的参数值，
139. * 将参数值拼接为操作内容
140. \*/
141. public String adminOptionContent(Object\[] args, String mName) throws Exception{
142. if (args == null) {
143. return null;
144. }
145. StringBuffer rs = new StringBuffer();
146. rs.append(mName);
147. String className = null;
148. int index = 1;
149. // 遍历参数对象
150. for (Object info : args) {
151. //获取对象类型
152. className = info.getClass().getName();
153. className = className.substring(className.lastIndexOf(".") + 1);
154. rs.append("[参数" + index + "，类型：" + className + "，值：");
155. // 获取对象的所有方法
156. Method\[] methods = info.getClass().getDeclaredMethods();
157. // 遍历方法，判断get方法
158. for (Method method : methods) {
159. String methodName = method.getName();
160. // 判断是不是get方法
161. if (methodName.indexOf("get") == -1) {// 不是get方法
162. continue;// 不处理
163. }
164. Object rsValue = null;
165. try {
166. // 调用get方法，获取返回值
167. rsValue = method.invoke(info);
168. if (rsValue == null) {//没有返回值
169. continue;
170. }
171. } catch (Exception e) {
172. continue;
173. }
174. //将值加入内容中
175. rs.append("(" + methodName + " : " + rsValue + ")");
176. }
177. rs.append("]");
178. index++;
179. }
180. return rs.toString();
181. }
182. }

 

 

 

**9、对管理员登录操作进行日志记录**

 

还记得[《使用Spring Security实现权限管理》](http://hotstrong.iteye.com/blog/1160153)一文中第7步提到的两个类吗？其中LoginSuccessHandler类中可以记录管理员的登录操作，代码如下：

 

 

Java代码  [![收藏代码](http://hotstrong.iteye.com/images/icon_star.png)]()

01. package com.xxx.security;
02. import java.io.IOException;
03. import java.util.Date;
04. import javax.servlet.ServletException;
05. import javax.servlet.http.HttpServletRequest;
06. import javax.servlet.http.HttpServletResponse;
07. import org.springframework.beans.factory.annotation.Autowired;
08. import org.springframework.security.core.Authentication;
09. import org.springframework.security.core.userdetails.UserDetails;
10. import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
11. import com.xxx.pojo.Log;
12. import com.xxx.service.LogService;
13. /\**
14. * 处理管理登录日志
15. \*
16. \*/
17. public class LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler{
18. @Autowired
19. private LogService logService;//日志记录Service
20. @Override
21. public void onAuthenticationSuccess(HttpServletRequest request,
22. HttpServletResponse response, Authentication authentication) throws IOException,
23. ServletException {
24. UserDetails userDetails = (UserDetails)authentication.getPrincipal();
25. //创建日志对象
26. Log log = new Log();
27. log.setUserid(logService.loginUserId());//设置管理员id
28. log.setCreatedate(new Date());//操作时间
29. log.setContent("管理员 " + userDetails.getUsername());//操作内容
30. log.setOperation("登录");//操作
31. logService.log(log);//添加日志
32. super.onAuthenticationSuccess(request, response, authentication);
33. }
34. }

 

 

 

**10、在applicationContext-services.xml中加入新的配置**

 

**applicationContext-services.xml中加入了Aspectj配置以及新增的管理员Service、日志记录Service配置：**

 

 

Xml代码  [![收藏代码](http://hotstrong.iteye.com/images/icon_star.png)]()

01. &lt;?xml version="1.0" encoding="UTF-8"?&gt;
02. &lt;beans xmlns="http://www.springframework.org/schema/beans"
03. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
04. xmlns:aop="http://www.springframework.org/schema/aop"
05. xmlns:tx="http://www.springframework.org/schema/tx"
06. xsi:schemaLocation="
07. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
08. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
09. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"&gt;
10. &lt;!-- 加入Aspectj配置 --&gt;
11. &lt;aop:aspectj-autoproxy /&gt;
12. &lt;bean id="logAspect" class="com.xxx.aop.LogAspect" /&gt;
13. &lt;!-- 电影业务逻辑对象 --&gt;
14. &lt;bean id="filmService" class="com.xxx.service.FilmServiceImpl"&gt;&lt;/bean&gt;
15. &lt;!-- 管理员业务逻辑对象 --&gt;
16. &lt;bean id="adminService" class="com.xxx.service.AdminServiceImpl"&gt;&lt;/bean&gt;
17. &lt;!-- 日志记录业务逻辑对象 --&gt;
18. &lt;bean id="logService" class="com.xxx.service.LogServiceImpl"&gt;&lt;/bean&gt;
19. &lt;/beans&gt;

 

 

 

**11、配置成功后分别进行登录、添加、修改、删除****影片操作，日志记录表的内容如下：**

 

 

![](http://hotstrong.iteye.com/upload/picture/pic/105146/c5ff2472-4420-3d5b-93f9-f7699360cd6e.jpg "点击查看原始大小图片")

 

 

**参考文章：**

**[MyBatis 1章 入门(使用MyBatis完成CRUD)](http://hotstrong.iteye.com/blog/1087867)**

**[使用Spring Security实现权限管理](http://hotstrong.iteye.com/blog/1160153)**

**[使用ajax gson增强用户体验](http://hotstrong.iteye.com/blog/1164379)**