当前位置:首页 > spring - AOP配置日志
转自--dongsw
想在项目里面使用log4j做日志的记录,但现在需要写日志的类很多,而且写日志的代码都是雷同的,所以就利用spring的aop来完成写日志的任务。 首先,需要将log4j先配置好在web.xml中加入解析器servlet的配置 Java代码
1.
2.
3.
4. 5.
6.
7.
9. org.springframework.web.util.Log4jConfigServlet 10.
11.
14.
15.
16. org.springframework.web.util.Log4jConfigListener 17. 18.
之后,由于我项目当中配置了大量的service类,类名都以Service结尾,为了方便配置使用spring当中的BeanNameAutoProxyCreator类进行aop配置。 在spring配置文件中配置如下: Java代码
1. > 2. 3. \ 4. .autoproxy.BeanNameAutoProxyCreator\5. 6. 7. 8. y> 9. 10. 12. 15. 17. 再来就是写Advice类了也就是配置中的LoggerAdvice,代码如下: Java代码 1. public class LoggerAdvice implements MethodBeforeAdvice, 2. AfterReturningAdvice,ThrowsAdvice { 3. public void before(Method method, Object[] args, 4. Object target)throws Throwable { 5. Logger logger = Logger.getLogger(target.getClass()); 6. logger.debug(\ 7. logger.debug(\8. } 9. 10.public void afterReturning(Object retuVal, Method method, 11. Object[] args,Object target) throws Throwable { 12. Log log = LogFactory.getLog(target.getClass()); 13. //do log 14. } 15. 16.public void afterThrowing(Method method,Object[] args, 17. Object target,Exception ex){ 18. Logger logger = Logger.getLogger(target.getClass()); 19. logger.error(\数据处理时发生异常\20. } 21.} 注释形式的AOP编程,便利的实现了运行时对类及其方法的监控及干预,使生活变得更美好。 —— 《Seraph川上曰》 环境 :系统开发过程中,我们都曾实现过将系统元数据或字典表添加到缓存中,以便程序调用,减少数据库访问IO。 问题 :在用户通过前端页面更新系统字典表时,需手工刷新系统缓存,操作很不友好。 解决方案 :监听持久层DAO方法的调用,对于目标表的insert,update,delete操作进行相应的系统缓存更新。 示例环境 :Spring2.5 + iBatis + AspectJ 参考书目 :Spring 2.5 Aspect-Oriented Programming Spring AOP自动代理的XML配置 Xml代码 1. 2. s:xsi=\ xmlns:aop=\tp://www.springframework.org/schema/aop\ xsi:schemaLocation=\tp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
共分享92篇相关文档