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

网友投稿 262 2022-12-04


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

{

MethodSignatuhttp://re 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.ghttp://etTarget().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机制确实能够大大减少代码量,很容易的就实现了日志的管理


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:spring+mybatis实现图书管理系统
下一篇:SpringBoot整合SSO(single sign on)单点登录
相关文章

 发表评论

暂时没有评论,来抢沙发吧~