Spring AOP自定义Annotation搭配log4j做日志
来源:互联网 发布:淘宝店铺街入口 编辑:程序博客网 时间:2024/06/06 03:41
概况:
项目框架:Spring4,Hibernate4,SpringMVC
项目结构:使用了最常用的model,dao,service,controller
我的项目是在service层控件事务,运行日志也加在service层。
aop作用的是xml配置
涉及到的点:
1、自定义Annotation
2、使用SpringAOP
3、AOP通知参数
步骤:
1、自定义Annotation
@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)public @interface LogInfo {public String value() default"";}
介绍一下,只有一个默认值,下面会介绍怎么使用。
2、给service方法添加自定义Annotation
@LogInfo("获取验证码(老婆设备号),")@Overridepublic HusRegister getCheckCode(String wifeDevice) {HusRegister husRegister = registerDao.findHusRegisterByWifeDevice(wifeDevice);return initRegister(husRegister, wifeDevice);}重要的点:
1、service层也是面向接口编程,这个Annotation要加在实现类的方法中,不能加在接口方法中,否则AOP获取不到
2、如图,自定义的Annotation里面增加的是日志要输出的,就是这个方法的作用,还有方法的参数作用,最后在日志中可以看到
3、注意,这个service已经被Spring管理,已经加入事务。同时也加入了AOP。
3、SpringAOP的配置
<aop:aspect id="registerLog" ref="registerLog"><aop:pointcutexpression="execution(* hus.register.service.*.*(..)) and @annotation(logInfo)"id="servicePointcut" /><aop:after method="log" pointcut-ref="servicePointcut"arg-names="logInfo" /></aop:aspect>
如图,是AOP其中一个的配置,expression定义了在哪些方法中加入,重点是后面的,
and @annotation(logInfo)
<aop:after method="log" pointcut-ref="servicePointcut"arg-names="logInfo" />logInfo是我自定义的参数。下面看一下log方法就知道怎么回事了。
@Component("registerLog")public class RegisterLog {public static final Logger LOGGER = Logger.getLogger(RegisterLog.class);public void log(JoinPoint joinPoint, LogInfo logInfo) {LOGGER.info(logInfo.value() + StaticTool.toJSon(joinPoint.getArgs()));}}@Component是声明这个组件,使它被Spring控制,声明的id是registerLog,所以xml中的 ref="registerLog"使用的是它
上面的xml中aop:after,看一下这个配置,再看一下log方法,第二个参数logInfo,就是这么来了,
第一个参数,是默认就会加入的,不用在arg-names里面声明
4、效果
log4j的配置就不贴出来了,给大家看一下日志的效果:
2016-07-28 14:21:59 INFO RegisterLog:13 : 获取验证码(设备号),["863121023684624"]
获取了Annotation,并把它当作日志输出,这样我们就可以非常容易地控制方法的执行时候的日志记录,并且可以记录到参数,以后记录的时候会非常方便。
0 0
- Spring AOP自定义Annotation搭配log4j做日志
- 使用spring aop结合log4j做日志
- 使用spring aop结合log4j做日志
- Spring aop +自定义annotation
- 基于Spring的AOP实现自定义annotation操作日志
- 基于Spring的AOP实现自定义annotation操作日志
- spring aop记录日志,Log4j
- spring AOP annotation 实现日志服务
- spring aop 做请求日志
- Spring AOP+Log4j记录项目日志
- spring aop 切面记录log4j日志
- spring的学习-common-logging搭配log4j配置项目日志
- 日志搭配commons-logging+log4j
- @interface 自定义annotation 通过AOP来实现人员操作日志
- @interface 自定义annotation 通过AOP来实现人员操作日志
- spring的aop做日志的控制
- Spring aop切面做日志处理操作
- spring aop+zabbix做日志监控
- Swift根据日期字符串返回日期是星期几
- Redis 集群教程
- HDU5772 String problem
- mongodb导出数据库到文本文件
- Maven实战(九)——打包的技巧
- Spring AOP自定义Annotation搭配log4j做日志
- JAVA中参数传递的迷惑点
- select into from 和 insert into select 的用法和区别
- Spring Data JPA书写原生态sql拼接
- bzoj1877(费用流)
- Shell编程---基础
- Android——从本地图库上传图片至服务器
- centos配置epel和remi源
- 湖南省第八届省赛 病毒 (最长公共上升子序列)