Spring框架基于AOP实现简单日志管理步骤解析

这篇文章主要介绍了Spring框架基于AOP实现简单日志管理步骤解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

SPringAOP的使用

技术概述,描述这个技术是做什么?学习该技术的原因,技术的难点在哪里。
为了实现项目管理员端的操作数据库日志,便于方便所以利用Spring框架的AOP机制进行实现,项目的难点在于如果设置切入点,如何获取参数。

技术详述,描述你是如何实现和使用该技术的,要求配合代码和流程图详细描述。可以再细分多个点,分开描述各个部分。

在applicationContext.xml中开启AOP代理


自定义一个注解

 @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface LogAnno { String operatorType(); }

编写一个切面类

 @Component @Aspect public class LogAopAspect { @Autowired LogtableService logtableService;//Logtable为数据库中的一张表,用于存储日志信息 @Around("@annotation(qj.admin.aspect.LogAnno)")//设定需要捕获的标签 public Object around(ProceedingJoinPoint pjp) throws Throwable { MethodSignature methodSignature =(MethodSignature)pjp.getSignature(); Method method = methodSignature.getMethod(); String targetName = pjp.getTarget().getClass().getName(); System.out.println("增强的类是:"+targetName); System.out.println("增强的方法是:"+method.getName()); Method realMethod = pjp.getTarget().getClass().getDeclaredMethod(methodSignature.getName(), method.getParameterTypes()); LogAnno logAnno = realMethod.getAnnotation(LogAnno.class);//获取注解的方法上的自定义标签类 String operatortype = logAnno.operatorType();//获取到自定义标签上的注解如“修改账户状态” //String operatortype = "修改用户积分"; AdminLog adminLog = new AdminLog(); adminLog.setOperatortype(operatortype); adminLog.setOperator("123"); Object resultObject = null; Object [] parameter = pjp.getArgs();//获取注解的方法的传入参数 try { resultObject = pjp.proceed(); adminLog.setOperatorresult("正常 "+Arrays.toString(parameter)); } catch (Exception e) { // TODO: handle exception adminLog.setOperatorresult("失败"); } finally { adminLog.setOperatordate(new Date()); logtableService.addLog(adminLog); } return resultObject; }

用自定义注解注解一个方法

 @LogAnno(operatorType = "修改账户状态") public void handleUser(int IDNumber, int type) { User user = userDAO.get(IDNumber); userDAO.update(user, type); }

项目目录结构

技术使用中遇到的问题和解决过程。要求问题的描述和解决有一定的内容,不能草草概括。要让遇到相关问题的人看了你的博客之后能够解决该问题。

刚刚开始的时候时候仅仅利用Method method = methodSignature.getMethod();来获取当前增强的方法,但是在接下来的LogAnno logAnno = method.getAnnotation(LogAnno.class);中get到的logAnno类为空,而上面通过打印System.out.println("增强的方法是:"+method.getName());显示增加的方法并没有错误,导致这就陷入了我的知识盲区,经过查找资料,大部分教程都说在自定义注解类中添加@Retention(RetentionPolicy.RUNTIME)即可解决问题,但是我添加之后还是同样的问题,最后意识到,可能这方法所获取的函数是两个不同的函数,最后又经过查找最终发现原来是这个aop拦截的是ServiceImpl的一个方法,然后这个ServiceImpl又启动了事务管理,而事务管理又是基于AOP的。

也就是说,这个权限的@Around的切面拦截的是个代理对象的方法,而代理对象的方法是不会把原来父类中的方法的注解加上去的,所以这里这个注解的对象为null。

最后运用Method realMethod = pjp.getTarget().getClass().getDeclaredMethod(methodSignature.getName(), method.getParameterTypes());获取到了真正需要的增强的函数。

总结

利用Spring的AOP机制确实能够大大减少代码量,很容易的就实现了日志的管理

以上就是Spring框架基于AOP实现简单日志管理步骤解析的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Java