最近刚接手一个项目,在项目的开始阶段,我们的架构师分配了个任务给我,让我利用spring的切面技术做一个日志管理的案例。要求很简单,就是需要记录:谁在什么时候对谁做了什么操作,同时在日志的描述中还要有修改前后内容的对比。话说两句话是挺简单的,但是对于对spring只有初学者水平的我还是有点难度的,于是各种百度,各种谷歌,各种想。终于在这篇http://kaowww153.iteye.com/blog/603891博客中得到启发,但是里面的内容写的还是不够完整,和我的需求也有些不一样。经过多次的修改和测试,终于成功通过。今天闲来无事,写个博文,以备下次需要做好笔记。话不多说,把过程写下:
1.首先创建一个自定义注解
package com.cstp.custom.interfaces;

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

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface RecordLog {

}
2.写一个过滤方法,这个方法是实现MethodIntherceptor接口的。
package com.cstp.custom.interfaces;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import com.cstp.jdbc.dao.systemLogDao;
import com.cstp.jdbc.dao.impl.systemLogDaoImpl;
import com.cstp.jdbc.vo.SystemLog;
import com.cstp.jdbc.vo.User;

public class LogAroundInterceptor implements MethodInterceptor {
private systemLogDao systemLogDao = new systemLogDaoImpl();

@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
// TODO Auto-generated method stub
Object returnObject;
Object newObj = null;
Object operatObj = null;
HttpServletRequest request = null;
Method method = invocation.getMethod();
if (method.isAnnotationPresent(RecordLog.class)) {
Object[] arguments = invocation.getArguments();

if (null != arguments) {
newObj = arguments[0];//新对象
operatObj = arguments[1];//操作人
if (arguments[2] instanceof HttpServletRequest) {
request = (HttpServletRequest)arguments[2]; //通过session把旧对象传过来作为新旧对象的比较
}
SystemLog systemLog = getSysLog(getOperaType(method.getName()), newObj, operatObj, request);
System.out.println(systemLog);
systemLogDao.addLog(systemLog);
}
returnObject = invocation.proceed(); // 执行被拦截的方法
} else {
returnObject = invocation.proceed(); // 执行被拦截的方法
}
return returnObject;
}

public int getOperaType(String methodName) {
int type = 0;
if (methodName.startsWith("save") || methodName.startsWith("add") || methodName.startsWith("insert")) {
type = 1;//增
} else if (methodName.startsWith("delete") || methodName.startsWith("del")) {
type = 2;//删
} else if (methodName.startsWith("update")){
type = 3;//改
}
return type;
}

public SystemLog getSysLog(int type, Object newObj, Object operator,HttpServletRequest request) {
StringBuffer sysContent = new StringBuffer();
SystemLog systemLog = new SystemLog();
Object oldObject = request.getSession().getAttribute("oldUser");
if (type != 1 && type != 2 && type != 3) {
System.out.println("此方法不能被记录日志");
return null;
}
if (newObj instanceof User) {
User user = (User) newObj;
sysContent.append("用户:");
if (type == 1) {
sysContent.append(user.getName()).append("被保存.");
} else if (type == 2) {
// sysContent.append(user.getDeleteUser()).append(
// "删除了用户:" + user.getUniqueUserName());
}
}
return systemLog;
}

}

3.applicationContext.xml里配置
<bean id="common" class="com.cstp.jdbc.test.Common">
</bean>

<aop:config>
<aop:pointcut id="logPointCuts"
expression="execution(* com.cstp.jdbc.test.*.*(..))" />
<aop:advisor pointcut-ref="logPointCuts" advice-ref="springMethodInterceptor" />
</aop:config>

<bean id="springMethodInterceptor" class="com.cstp.custom.interfaces.LogAroundInterceptor">
</bean>
</beans>
4.我的实体类common
@RecordLog
public void update(User user, User opeartor, HttpServletRequest request) {

UserDao userDao = new UserDaoImpl();
userDao.updateUser(user);
System.out.println("修改成功");
}

5.在servlet测试
UserDao userDao = new UserDaoImpl();
BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
Common c = (Common) factory.getBean("common");
User user = new User();
user.setId(2);
user.setName("杰");
user.setPassword("123456");
user.setAge(18);
user.setSex("女");
User opeartor = userDao.findAllUserById(3);

User oldUser = userDao.findAllUserById(2);
HttpSession session = request.getSession();
session.setAttribute("oldUser", oldUser);

c.update(user, opeartor, request);
测试通过,我所需要的新旧对象,以及操作人,时间,描述等都可以在getSysLog()方法中获取,至于如何添加就简单啦,就不写上了。
6.使用方法很简单了:在需要添加日志的方法上加上我们的注解@RecordLog就可以了(就像我common类里的update方法一样)。

利用spring AOP注解实现日志管理相关推荐

  1. 利用spring aop统一处理异常和打日志

    利用spring aop统一处理异常和打日志 spring aop的概念,很早就写博客介绍了,现在在工作中真正使用. 我们很容易写出的代码 我们很容易写出带有很多try catch 和 logger. ...

  2. Spring MVC 中使用AOP 进行统一日志管理--XML配置实现

    1.介绍 上一篇博客写了使用AOP进行统一日志管理的注解版实现,今天写一下使用XML配置实现版本,与上篇不同的是上次我们记录的Controller层日志,这次我们记录的是Service层的日志.使用的 ...

  3. 利用Spring AOP 更新memcached 缓存策略的实现(一)

    本人参考文档:http://blog.csdn.net/ajun_studio/article/details/7343781 memcached批量删除解决方案:http://tech.ddvip. ...

  4. spring AOP注解失效原因

    目录 @Transactional @Async等注解不起作用 JDK动态代理 Spring AOP注解失效原因及解决 原因1:同一个类中,方法A调用方法B(方法B上加有注解),注解无效 原因2:AO ...

  5. spring aop 注解

    spring Aop 注解 Aop 术语 AOP 的特性术语,不同的翻译还会不一样,得在过程中理解 横切关注点:跨越程序多个模块的方法或功能.即与业务逻辑无关,但我们也要关注的部分,就是横切关注点.如 ...

  6. Spring AOP注解方式实现

    简介 上文已经提到了Spring AOP的概念以及简单的静态代理.动态代理简单示例,链接地址:https://www.cnblogs.com/chenzhaoren/p/9959596.html 本文 ...

  7. Spring AOP注解为什么失效?90%Java程序员不知道

    转载自 Spring AOP注解为什么失效?90%Java程序员不知道 使用Spring Aop注解的时候,如@Transactional, @Cacheable等注解一般需要在类方法第一个入口的地方 ...

  8. java spring aop 注解包_Spring AOP 注解配置实例

    Spring AOP注解例子 一:导入相关jar包. 首先导入Spring的相关包(这里就不多说了,我这里是3.2.4版本的) 然后导入AOP注解的相关包(不是spring的包)aspectjrt-1 ...

  9. spring aop 切面添加日志

    这是一个非常简单的spring aop切面添加日志的程序,下面来看一下这个程序 1.程序使用jar包 2.切面类LoggingAspect.java package com.cailei.aop.as ...

最新文章

  1. JVM调优——之CMS GC日志分析
  2. sql delete删除两个表_超强干货!SQL语法大合集
  3. python循环10次1001python循环10次_Python循环题怎么做?
  4. Linux下MPlayer的安装
  5. 深度残差网络的无人机多目标识别
  6. 铠侠 RC10 固态硬盘寿命暴力写入测试:1100pe 毫发无损
  7. PLSQL_案例优化系列_明白索引是如何让SQL运行飞快(案例5)
  8. 微软发布“史无前例”的恶意软件数据集,设17万奖金征集预测算法
  9. cfree mysql_如何配置CFree才能开发MySql数据库应用 | 学步园
  10. 转帖:算法好学吗?——《大话数据结构》读者书评
  11. 文本编辑器(Editor)and 文件上传功能
  12. vs2010 sp1 安装错误,重新安装错误
  13. 欢迎来到Wagtail的文档
  14. 生活美学 | 8种咖啡冲煮器具分别有什么特点
  15. 智能路由器要成功 该怎样修炼穿墙术?
  16. token 微信access 过期_.Net微信开发之如何解决access_token过期问题
  17. PCIe设备在一个系统中是如何发现与访问的
  18. 常见鸟的种类及特点_鸟的分类
  19. public class A implements B{} --java
  20. 数据结构翻转课堂答疑实录——顺序表

热门文章

  1. 支持向量机SVM算法原理
  2. Java多线程(十一)之线程池深入分析(上)
  3. python--列表与字典
  4. org.springframework.web.multipart.MultipartException: The current request is not a multipart request
  5. 使用PuTTY、Xshell远程连接Linux,密钥认证连接
  6. 单链表的整表创建以及整表删除
  7. 你可以通过这13种方法帮助Linux发展
  8. hashCode()方法的性能优化
  9. opencms的主工作区文件研究
  10. Linux ALSA声卡驱动之七:ASoC架构中的Codec