---
title: "SpringAOP拦截Controller,Service实现日志管理(自定义注解的方式)"
author: "tiangai"
date: "2014-08-13T22:17:50Z"
tags: ["AOP", "MVC", "Spring", "controller", "日志管理"]
categories: ["企业架构"]
slug: "springaop-controller-service"
draft: false
lastmod: "2014-08-13T22:50:47Z"
id: 2103708
url: "https://tiangai.iteye.com/blog/2103708"
---

从业近二，三年了，第一次写博客，平时做做脚手架或者架构一些基础框架然后给大家使用或者自己总结翻译一些文档。虽然是第一次但是我还是要拿Spring开刀。希望张开涛，涛兄看到的时候不要喷我，给我一点指导。

         首先我们为什么需要做日志管理，在现实的上线中我们经常会遇到系统出现异常或者问题。这个时候就马上打开CRT或者SSH连上服务器拿日子来分析。受网络的各种限制。于是我们就想为什么不能直接在管理后台查看报错的信息呢。于是日志管理就出现了。

         其次个人觉得做日志管理最好的是Aop，有的人也喜欢用拦截器。都可以，在此我重点介绍我的实现方式。

         Aop有的人说拦截不到Controller。有的人说想拦AnnotationMethodHandlerAdapter截到Controller必须得拦截org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter。

首先Aop可以拦截到Controller的，这个是毋容置疑的其次须拦截AnnotationMethodHandlerAdapter也不是必须的。最起码我没有验证成功过这个。我的Spring版本是4.0.3。

         Aop之所以有的人说拦截不到Controller是因为Controller被jdk代理了。我们只要把它交给cglib代理就可以了。

第一步定义两个注解：

 

Java代码 [![复制代码](/images/icon_copy.gif)](/admin/blogs/2103708/edit "复制代码")

01. **package** com.annotation;
02. **import** java.lang.annotation.\*;
03. /\**
04. \*自定义注解 拦截Controller
05. \*/
06. @Target({ElementType.PARAMETER, ElementType.METHOD})
07. @Retention(RetentionPolicy.RUNTIME)
08. @Documented
09. **public** **@interface** SystemControllerLog {
10. String description() **default** "";
11. }
12. **package** com.annotation;
13. **import** java.lang.annotation.\*;
14. /\**
15. \*自定义注解 拦截service
16. \*/
17. @Target({ElementType.PARAMETER, ElementType.METHOD})
18. @Retention(RetentionPolicy.RUNTIME)
19. @Documented
20. **public** **@interface** SystemServiceLog {
21. String description() **default** "";
22. }

第二步创建一个切点类：

 

 

Java代码 [![复制代码](/images/icon_copy.gif)](/admin/blogs/2103708/edit "复制代码")

001. **package** com.annotation;
002. **import** com.model.Log;
003. **import** com.model.User;
004. **import** com.service.LogService;
005. **import** com.util.DateUtil;
006. **import** com.util.JSONUtil;
007. **import** com.util.SpringContextHolder;
008. **import** com.util.WebConstants;
009. **import** org.aspectj.lang.JoinPoint;
010. **import** org.aspectj.lang.annotation.\*;
011. **import** org.slf4j.Logger;
012. **import** org.slf4j.LoggerFactory;
013. **import** org.springframework.stereotype.Component;
014. **import** org.springframework.web.context.request.RequestContextHolder;
015. **import** org.springframework.web.context.request.ServletRequestAttributes;
016. **import** javax.annotation.Resource;
017. **import** javax.servlet.http.HttpServletRequest;
018. **import** javax.servlet.http.HttpSession;
019. **import** java.lang.reflect.Method;
020. /\**
021. * 切点类
022. * @author tiangai
023. * @since 2014-08-05 Pm 20:35
024. * @version 1.0
025. \*/
026. @Aspect
027. @Component
028. **public** **class** SystemLogAspect {
029. //注入Service用于把日志保存数据库
030. @Resource
031. **private** LogService logService;
032. //本地异常日志记录对象
033. **private** **static** **final** Logger logger = LoggerFactory.getLogger(SystemLogAspect.**class**);
034. //Service层切点
035. @Pointcut("@annotation(com.annotation.SystemServiceLog)")
036. **public** **void** serviceAspect() {
037. }
038. //Controller层切点
039. @Pointcut("@annotation(com.annotation.SystemControllerLog)")
040. **public** **void** controllerAspect() {
041. }
042. /\**
043. * 前置通知 用于拦截Controller层记录用户的操作
044. \*
045. * @param joinPoint 切点
046. \*/
047. @Before("controllerAspect()")
048. **public** **void** doBefore(JoinPoint joinPoint) {
049. HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
050. HttpSession session = request.getSession();
051. //读取session中的用户
052. User user = (User) session.getAttribute(WebConstants.CURRENT\_USER);
053. //请求的IP
054. String ip = request.getRemoteAddr();
055. **try** {
056. //\*========控制台输出=========\*//
057. System.out.println("=====前置通知开始=====");
058. System.out.println("请求方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));
059. System.out.println("方法描述:" + getControllerMethodDescription(joinPoint));
060. System.out.println("请求人:" + user.getName());
061. System.out.println("请求IP:" + ip);
062. //\*========数据库日志=========\*//
063. Log log = SpringContextHolder.getBean("logxx");
064. log.setDescription(getControllerMethodDescription(joinPoint));
065. log.setMethod((joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));
066. log.setType("0");
067. log.setRequestIp(ip);
068. log.setExceptionCode(**null**);
069. log.setExceptionDetail(**null**);
070. log.setParams(**null**);
071. log.setCreateBy(user);
072. log.setCreateDate(DateUtil.getCurrentDate());
073. //保存数据库
074. logService.add(log);
075. System.out.println("=====前置通知结束=====");
076. } **catch** (Exception e) {
077. //记录本地异常日志
078. logger.error("==前置通知异常==");
079. logger.error("异常信息:{}", e.getMessage());
080. }
081. }
082. /\**
083. * 异常通知 用于拦截service层记录异常日志
084. \*
085. * @param joinPoint
086. * @param e
087. \*/
088. @AfterThrowing(pointcut = "serviceAspect()", throwing = "e")
089. **public** **void** doAfterThrowing(JoinPoint joinPoint, Throwable e) {
090. HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
091. HttpSession session = request.getSession();
092. //读取session中的用户
093. User user = (User) session.getAttribute(WebConstants.CURRENT\_USER);
094. //获取请求ip
095. String ip = request.getRemoteAddr();
096. //获取用户请求方法的参数并序列化为JSON格式字符串
097. String params = "";
098. **if** (joinPoint.getArgs() != **null** && joinPoint.getArgs().length &gt; 0) {
099. **for** (**int** i = 0; i &lt; joinPoint.getArgs().length; i++) {
100. params += JSONUtil.toJsonString(joinPoint.getArgs()\[i]) + ";";
101. }
102. }
103. **try** {
104. /\*========控制台输出=========\*/
105. System.out.println("=====异常通知开始=====");
106. System.out.println("异常代码:" + e.getClass().getName());
107. System.out.println("异常信息:" + e.getMessage());
108. System.out.println("异常方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));
109. System.out.println("方法描述:" + getServiceMthodDescription(joinPoint));
110. System.out.println("请求人:" + user.getName());
111. System.out.println("请求IP:" + ip);
112. System.out.println("请求参数:" + params);
113. /\*==========数据库日志=========\*/
114. Log log = SpringContextHolder.getBean("logxx");
115. log.setDescription(getServiceMthodDescription(joinPoint));
116. log.setExceptionCode(e.getClass().getName());
117. log.setType("1");
118. log.setExceptionDetail(e.getMessage());
119. log.setMethod((joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));
120. log.setParams(params);
121. log.setCreateBy(user);
122. log.setCreateDate(DateUtil.getCurrentDate());
123. log.setRequestIp(ip);
124. //保存数据库
125. logService.add(log);
126. System.out.println("=====异常通知结束=====");
127. } **catch** (Exception ex) {
128. //记录本地异常日志
129. logger.error("==异常通知异常==");
130. logger.error("异常信息:{}", ex.getMessage());
131. }
132. /\*==========记录本地异常日志==========\*/
133. logger.error("异常方法:{}异常代码:{}异常信息:{}参数:{}", joinPoint.getTarget().getClass().getName() + joinPoint.getSignature().getName(), e.getClass().getName(), e.getMessage(), params);
134. }
135. /\**
136. * 获取注解中对方法的描述信息 用于service层注解
137. \*
138. * @param joinPoint 切点
139. * @return 方法描述
140. * @throws Exception
141. \*/
142. **public** **static** String getServiceMthodDescription(JoinPoint joinPoint)
143. **throws** Exception {
144. String targetName = joinPoint.getTarget().getClass().getName();
145. String methodName = joinPoint.getSignature().getName();
146. Object\[] arguments = joinPoint.getArgs();
147. Class targetClass = Class.forName(targetName);
148. Method\[] methods = targetClass.getMethods();
149. String description = "";
150. **for** (Method method : methods) {
151. **if** (method.getName().equals(methodName)) {
152. Class\[] clazzs = method.getParameterTypes();
153. **if** (clazzs.length == arguments.length) {
154. description = method.getAnnotation(SystemServiceLog.**class**).description();
155. **break**;
156. }
157. }
158. }
159. **return** description;
160. }
161. /\**
162. * 获取注解中对方法的描述信息 用于Controller层注解
163. \*
164. * @param joinPoint 切点
165. * @return 方法描述
166. * @throws Exception
167. \*/
168. **public** **static** String getControllerMethodDescription(JoinPoint joinPoint) **throws** Exception {
169. String targetName = joinPoint.getTarget().getClass().getName();
170. String methodName = joinPoint.getSignature().getName();
171. Object\[] arguments = joinPoint.getArgs();
172. Class targetClass = Class.forName(targetName);
173. Method\[] methods = targetClass.getMethods();
174. String description = "";
175. **for** (Method method : methods) {
176. **if** (method.getName().equals(methodName)) {
177. Class\[] clazzs = method.getParameterTypes();
178. **if** (clazzs.length == arguments.length) {
179. description = method.getAnnotation(SystemControllerLog.**class**).description();
180. **break**;
181. }
182. }
183. }
184. **return** description;
185. }
186. }

 第三步把Controller的代理权交给cglib

 

在实例化ApplicationContext的时候需要加上

 

Xml代码 [![复制代码](/images/icon_copy.gif)](/admin/blogs/2103708/edit "复制代码")

1. &lt;!-- 启动对@AspectJ注解的支持 --&gt;
2. **&lt;aop:aspectj-autoproxy/&gt;**

 在调用Controller的时候AOP发挥作用所以在SpringMVC的配置文件里加上

 

 

Xml代码 [![复制代码](/images/icon_copy.gif)](/admin/blogs/2103708/edit "复制代码")

1. &lt;!--通知spring使用cglib而不是jdk的来生成代理方法 AOP可以拦截到Controller-**&gt;**
2. **&lt;aop:aspectj-autoproxy** proxy-target-class="true"**/&gt;**

 第四步使用

 

Controller层的使用

 

Java代码 [![复制代码](/images/icon_copy.gif)](/admin/blogs/2103708/edit "复制代码")

01. /\**
02. * 删除用户
03. \*
04. * @param criteria 条件
05. * @param id       id
06. * @param model    模型
07. * @return 数据列表
08. \*/
09. @RequestMapping(value = "/delete")
10. //此处为记录AOP拦截Controller记录用户操作
11. @SystemControllerLog(description = "删除用户")
12. **public** String del(Criteria criteria, String id, Model model, HttpSession session) {
13. **try** {
14. User user = (User) session.getAttribute(WebConstants.CURRENT\_USER);
15. **if** (**null** != user) {
16. **if** (user.getId().equals(id)) {
17. msg = "您不可以删除自己!";
18. criteria = userService.selectByCriteriaPagination(criteria);
19. } **else** {
20. //删除数据并查询出数据
21. criteria = userService.delete(id, criteria);
22. msg = "删除成功!";
23. }
24. }
25. } **catch** (Exception e) {
26. msg = "删除失败!";
27. } **finally** {
28. model.addAttribute("msg", msg);
29. model.addAttribute("criteria", criteria);
30. }
31. //跳转列表页
32. **return** "user/list";
33. }

 Service层的使用

 

 

Java代码 [![复制代码](/images/icon_copy.gif)](/admin/blogs/2103708/edit "复制代码")

01. /\**
02. * 按照分页查询
03. * @param criteria
04. * @return
05. \*/
06. //此处为AOP拦截Service记录异常信息。方法不需要加try-catch
07. @SystemServiceLog(description = "查询用户")
08. **public** Criteria&lt;User&gt; selectByCriteriaPagination(Criteria&lt;User&gt; criteria)
09. {
10. criteria.getList().get(0).getAccount();
11. //查询总数
12. **long** total=userMapper.countByCriteria(criteria);
13. //设置总数
14. criteria.setRowCount(total);
15. criteria.setList(userMapper.selectByCriteriaPagination(criteria));
16. **return**  criteria;
17. }

效果图

 

用户操作：

![](http://dl2.iteye.com/upload/attachment/0100/1600/79f6694c-385e-36ca-b644-e47de25ff4a7.jpg)  
 异常

![](http://dl2.iteye.com/upload/attachment/0100/1602/fdd7ebec-bfe5-3595-89a3-f9d81307626f.jpg)  
 初次写博客，写的不好敬请见谅。

下一篇将讲解微信6大消息接口的封装及开源我的封装敬请关注