SSH框架系列:Spring AOP应用记录日志Demo

简介:     分类: 【java】2013-12-10 18:53 724人阅读 评论(0) 收藏 举报 1.简介 Spring 中的AOP为Aspect Oriented Programming的缩写,面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。
 

 

分类: 【java】
1.简介
Spring 中的AOP为Aspect Oriented Programming的缩写,面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。以下是Spring AOP的小例子
2.例子简介
2.1切面aspect:Logging.java
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. /* 
  2.  * $filename: Logging.java,v $ 
  3.  * $Date: 2013-12-10  $ 
  4.  * Copyright (C) ZhengHaibo, Inc. All rights reserved. 
  5.  * This software is Made by Zhenghaibo. 
  6.  */  
  7. package edu.njupt.zhb;  
  8. /* 
  9.  *@author: ZhengHaibo   
  10.  *web:     http://blog.csdn.net/nuptboyzhb 
  11.  *mail:    zhb931706659@126.com 
  12.  *2013-12-10  Nanjing,njupt,China 
  13.  */  
  14. public class Logging {  
  15.       
  16.     public void beforeAdvice(){  
  17.         System.out.println("Logging:before... ");  
  18.     }  
  19.       
  20.     public void afterAdvice(){  
  21.         System.out.println("Logging:after... ");  
  22.     }  
  23.     /** 
  24.      *  
  25.      * @param retVal 函数的返回值 
  26.      */  
  27.     public void afterReturningAdvice(Object retVal){  
  28.         if(retVal==null){  
  29.             return;  
  30.         }  
  31.         System.out.println("Logging:return :"+retVal.toString());  
  32.     }  
  33.       
  34.     public void afterThrowingAdvice(IllegalArgumentException ex){  
  35.         System.out.println("Logging:exception:"+ex.toString());  
  36.     }  
  37. }  


2.2Bean: Student.java
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. /* 
  2.  * $filename: Student.java,v $ 
  3.  * $Date: 2013-12-10  $ 
  4.  * Copyright (C) ZhengHaibo, Inc. All rights reserved. 
  5.  * This software is Made by Zhenghaibo. 
  6.  */  
  7. package edu.njupt.zhb;  
  8. /* 
  9.  *@author: ZhengHaibo   
  10.  *web:     http://blog.csdn.net/nuptboyzhb 
  11.  *mail:    zhb931706659@126.com 
  12.  *2013-12-10  Nanjing,njupt,China 
  13.  */  
  14. public class Student {  
  15.     private String id;  
  16.     private String name;  
  17.     public String getId() {  
  18.         return id;  
  19.     }  
  20.     public void setId(String id) {  
  21.         this.id = id;  
  22.     }  
  23.     public String getName() {  
  24.         return name;  
  25.     }  
  26.     public void setName(String name) {  
  27.         this.name = name;  
  28.     }  
  29.     public void printThrowException(){  
  30.         System.out.println("Exception in Student.class...");  
  31.         throw new IllegalArgumentException("Exception from Student...");  
  32.     }  
  33.     public void print(String say){  
  34.         System.out.println("Say:"+say+",Name = "+name);  
  35.     }  
  36. }  


2.3xml文件配置
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  4.     xmlns:p="http://www.springframework.org/schema/p"  
  5.     xmlns:aop="http://www.springframework.org/schema/aop"  
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans   
  7.     http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
  8.     http://www.springframework.org/schema/aop   
  9.     http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">  
  10.     <!-- 切面类 -->  
  11.     <bean id="myLogging" class="edu.njupt.zhb.Logging"></bean>  
  12.     <!-- AOP配置 -->  
  13.     <aop:config>  
  14.        <aop:aspect id="logStudent" ref="myLogging">  
  15.            <!-- pointcut配置 -->  
  16.            <aop:pointcut id="allMethod" expression="execution(* edu.njupt.zhb.*.*(..))"/>  
  17.              <aop:before pointcut-ref="allMethod" method="beforeAdvice"/>  
  18.              <aop:after  pointcut-ref="allMethod" method="afterAdvice"/>  
  19.              <aop:after-returning pointcut-ref="allMethod" returning="retVal" method="afterReturningAdvice"/>  
  20.              <aop:after-throwing pointcut-ref="allMethod" throwing="ex" method="afterThrowingAdvice"/>  
  21.        </aop:aspect>  
  22.     </aop:config>  
  23.     <bean id="student" class="edu.njupt.zhb.Student">  
  24.       <property name="id" value="1012010638"></property>  
  25.       <property name="name" value="Haibo Zheng"></property>  
  26.     </bean>  
  27. </beans>  


2.4测试
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. package edu.njupt.zhb;  
  2. /* 
  3.  * $filename: TestMain.java,v $ 
  4.  * $Date: 2013-12-10  $ 
  5.  * Copyright (C) ZhengHaibo, Inc. All rights reserved. 
  6.  * This software is Made by Zhenghaibo. 
  7.  */  
  8.   
  9.   
  10. import org.springframework.context.ApplicationContext;  
  11. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  12.   
  13.   
  14. /* 
  15.  *@author: ZhengHaibo   
  16.  *web:     http://blog.csdn.net/nuptboyzhb 
  17.  *mail:    zhb931706659@126.com 
  18.  *2013-12-10  Nanjing,njupt,China 
  19.  */  
  20. public class TestMain {  
  21.   
  22.     /** 
  23.      * @param args 
  24.      */  
  25.     public static void main(String[] args) {  
  26.         // TODO Auto-generated method stub  
  27.         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");  
  28.         Student student = (Student)context.getBean("student");  
  29.         System.out.println("-------------");  
  30.         student.getId();  
  31.         System.out.println("-------------");  
  32.         student.getName();  
  33.         System.out.println("-------------");  
  34.         student.print("Hi,I am a student");  
  35.         System.out.println("-------------");  
  36.         try{  
  37.            student.printThrowException();  
  38.         }catch (Exception e) {  
  39.             // TODO: handle exception  
  40.             System.out.println(e.getMessage());  
  41.         }  
  42.           
  43.     }  
  44.   
  45. }  

2.5运行结果:
[plain]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. 2013-12-10 18:32:54 org.springframework.context.support.AbstractApplicationContext prepareRefresh  
  2. 信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@145e044: display name [org.springframework.context.support.ClassPathXmlApplicationContext@145e044]; startup date [Tue Dec 10 18:32:54 CST 2013]; root of context hierarchy  
  3. 2013-12-10 18:32:54 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions  
  4. 信息: Loading XML bean definitions from class path resource [applicationContext.xml]  
  5. 2013-12-10 18:32:54 org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory  
  6. 信息: Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext@145e044]: org.springframework.beans.factory.support.DefaultListableBeanFactory@1f4cbee  
  7. 2013-12-10 18:32:54 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons  
  8. 信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1f4cbee: defining beans [myLogging,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.aop.aspectj.AspectJPointcutAdvisor#0,org.springframework.aop.aspectj.AspectJPointcutAdvisor#1,org.springframework.aop.aspectj.AspectJPointcutAdvisor#2,org.springframework.aop.aspectj.AspectJPointcutAdvisor#3,allMethod,student]; root of factory hierarchy  
  9. -------------  
  10. Logging:before...   
  11. Logging:after...   
  12. Logging:return :1012010638  
  13. -------------  
  14. Logging:before...   
  15. Logging:after...   
  16. Logging:return :Haibo Zheng  
  17. -------------  
  18. Logging:before...   
  19. Say:Hi,I am a student,Name = Haibo Zheng  
  20. Logging:after...   
  21. -------------  
  22. Logging:before...   
  23. Exception in Student.class...  
  24. Logging:after...   
  25. Logging:exception:java.lang.IllegalArgumentException: Exception from Student...  
  26. Exception from Student...  

上述的方法只是在执行函数前,加一些自己的逻辑。如果完成更加复杂的功能,我们可能需要知道函数的名称以及函数的参数及其值等等信息。此时,我们只需要修改Logging类即可,可以修改为如下:(主要是使用了Spring aop中的JointPoint)
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. /* 
  2.  * $filename: Logging.java,v $ 
  3.  * $Date: 2013-12-10  $ 
  4.  * Copyright (C) ZhengHaibo, Inc. All rights reserved. 
  5.  * This software is Made by Zhenghaibo. 
  6.  */  
  7. package edu.njupt.zhb;  
  8.   
  9. import org.aspectj.lang.JoinPoint;  
  10.   
  11. /* 
  12.  *@author: ZhengHaibo   
  13.  *web:     http://blog.csdn.net/nuptboyzhb 
  14.  *mail:    zhb931706659@126.com 
  15.  *2013-12-10  Nanjing,njupt,China 
  16.  */  
  17. public class Logging {  
  18.       
  19.     public void beforeAdvice(JoinPoint jointPoint){  
  20.         Object methodArgs[] = jointPoint.getArgs();//获取切入点函数的参数  
  21.         for(Object arg:methodArgs){  
  22.             System.out.println("Logging:args type="+arg.getClass().getName());  
  23.             System.out.println("Logging:args value="+arg);  
  24.         }  
  25.         System.out.println("Logging:ClassName="+jointPoint.getTarget().getClass().getName());  
  26.         System.out.println("Logging:MethodName="+jointPoint.getSignature().getName());  
  27.         System.out.println("Logging:before... ");  
  28.     }  
  29.       
  30.     public void afterAdvice(){  
  31.         System.out.println("Logging:after... ");  
  32.     }  
  33.     /** 
  34.      *  
  35.      * @param retVal 函数的返回值 
  36.      */  
  37.     public void afterReturningAdvice(Object retVal){  
  38.         if(retVal==null){  
  39.             return;  
  40.         }  
  41.         System.out.println("Logging:return :"+retVal.toString());  
  42.     }  
  43.       
  44.     public void afterThrowingAdvice(IllegalArgumentException ex){  
  45.         System.out.println("Logging:exception:"+ex.toString());  
  46.     }  
  47. }  

此时的运行结果为:
 
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. 2013-12-10 19:44:07 org.springframework.context.support.AbstractApplicationContext prepareRefresh  
  2. 信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@145e044: display name [org.springframework.context.support.ClassPathXmlApplicationContext@145e044]; startup date [Tue Dec 10 19:44:07 CST 2013]; root of context hierarchy  
  3. 2013-12-10 19:44:07 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions  
  4. 信息: Loading XML bean definitions from class path resource [applicationContext.xml]  
  5. 2013-12-10 19:44:07 org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory  
  6. 信息: Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext@145e044]: org.springframework.beans.factory.support.DefaultListableBeanFactory@787d6a  
  7. 2013-12-10 19:44:07 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons  
  8. 信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@787d6a: defining beans [myLogging,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.aop.aspectj.AspectJPointcutAdvisor#0,org.springframework.aop.aspectj.AspectJPointcutAdvisor#1,org.springframework.aop.aspectj.AspectJPointcutAdvisor#2,org.springframework.aop.aspectj.AspectJPointcutAdvisor#3,allMethod,student]; root of factory hierarchy  
  9. -------------  
  10. Logging:ClassName=edu.njupt.zhb.Student  
  11. Logging:MethodName=getId  
  12. Logging:before...   
  13. Logging:after...   
  14. Logging:return :1012010638  
  15. -------------  
  16. Logging:ClassName=edu.njupt.zhb.Student  
  17. Logging:MethodName=getName  
  18. Logging:before...   
  19. Logging:after...   
  20. Logging:return :Haibo Zheng  
  21. -------------  
  22. Logging:args type=java.lang.String  
  23. Logging:args value=Hi,I am a student  
  24. Logging:args type=java.lang.Integer  
  25. Logging:args value=20  
  26. Logging:ClassName=edu.njupt.zhb.Student  
  27. Logging:MethodName=print  
  28. Logging:before...   
  29. Say:Hi,I am a student,Name = Haibo Zheng,age = 20  
  30. Logging:after...   
  31. -------------  
  32. Logging:ClassName=edu.njupt.zhb.Student  
  33. Logging:MethodName=printThrowException  
  34. Logging:before...   
  35. Exception in Student.class...  
  36. Logging:after...   
  37. Logging:exception:java.lang.IllegalArgumentException: Exception from Student...  
  38. Exception from Student...  

未经允许,不得用于商业目的
相关实践学习
通过日志服务实现云资源OSS的安全审计
本实验介绍如何通过日志服务实现云资源OSS的安全审计。
目录
相关文章
|
6月前
|
XML 安全 Java
使用 Spring 的 @Aspect 和 @Pointcut 注解简化面向方面的编程 (AOP)
面向方面编程(AOP)通过分离横切关注点,如日志、安全和事务,提升代码模块化与可维护性。Spring 提供了对 AOP 的强大支持,核心注解 `@Aspect` 和 `@Pointcut` 使得定义切面与切入点变得简洁直观。`@Aspect` 标记切面类,集中处理通用逻辑;`@Pointcut` 则通过表达式定义通知的应用位置,提高代码可读性与复用性。二者结合,使开发者能清晰划分业务逻辑与辅助功能,简化维护并提升系统灵活性。Spring AOP 借助代理机制实现运行时织入,与 Spring 容器无缝集成,支持依赖注入与声明式配置,是构建清晰、高内聚应用的理想选择。
673 0
|
10月前
|
监控 安全 Java
Spring AOP实现原理
本内容主要介绍了Spring AOP的核心概念、实现机制及代理生成流程。涵盖切面(Aspect)、连接点(Join Point)、通知(Advice)、切点(Pointcut)等关键概念,解析了JDK动态代理与CGLIB代理的原理及对比,并深入探讨了通知执行链路和责任链模式的应用。同时,详细分析了AspectJ注解驱动的AOP解析过程,包括切面识别、切点表达式匹配及通知适配为Advice的机制,帮助理解Spring AOP的工作原理与实现细节。
1469 13
|
5月前
|
XML Java 数据格式
《深入理解Spring》:AOP面向切面编程深度解析
Spring AOP通过代理模式实现面向切面编程,将日志、事务等横切关注点与业务逻辑分离。支持注解、XML和编程式配置,提供五种通知类型及丰富切点表达式,助力构建高内聚、低耦合的可维护系统。
|
6月前
|
Prometheus 监控 Java
日志收集和Spring 微服务监控的最佳实践
在微服务架构中,日志记录与监控对系统稳定性、问题排查和性能优化至关重要。本文介绍了在 Spring 微服务中实现高效日志记录与监控的最佳实践,涵盖日志级别选择、结构化日志、集中记录、服务ID跟踪、上下文信息添加、日志轮转,以及使用 Spring Boot Actuator、Micrometer、Prometheus、Grafana、ELK 堆栈等工具进行监控与可视化。通过这些方法,可提升系统的可观测性与运维效率。
612 1
日志收集和Spring 微服务监控的最佳实践
|
12月前
|
存储 Java 文件存储
微服务——SpringBoot使用归纳——Spring Boot使用slf4j进行日志记录—— logback.xml 配置文件解析
本文解析了 `logback.xml` 配置文件的详细内容,包括日志输出格式、存储路径、控制台输出及日志级别等关键配置。通过定义 `LOG_PATTERN` 和 `FILE_PATH`,设置日志格式与存储路径;利用 `&lt;appender&gt;` 节点配置控制台和文件输出,支持日志滚动策略(如文件大小限制和保存时长);最后通过 `&lt;logger&gt;` 和 `&lt;root&gt;` 定义日志级别与输出方式。此配置适用于精细化管理日志输出,满足不同场景需求。
2871 1
|
6月前
|
缓存 Java 应用服务中间件
Spring Boot配置优化:Tomcat+数据库+缓存+日志,全场景教程
本文详解Spring Boot十大核心配置优化技巧,涵盖Tomcat连接池、数据库连接池、Jackson时区、日志管理、缓存策略、异步线程池等关键配置,结合代码示例与通俗解释,助你轻松掌握高并发场景下的性能调优方法,适用于实际项目落地。
1110 5
|
12月前
|
Java 微服务 Spring
微服务——SpringBoot使用归纳——Spring Boot使用slf4j进行日志记录——使用Logger在项目中打印日志
本文介绍了如何在项目中使用Logger打印日志。通过SLF4J和Logback,可设置不同日志级别(如DEBUG、INFO、WARN、ERROR)并支持占位符输出动态信息。示例代码展示了日志在控制器中的应用,说明了日志配置对问题排查的重要性。附课程源码下载链接供实践参考。
1288 0
|
12月前
|
SQL Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot使用slf4j进行日志记录—— application.yml 中对日志的配置
在 Spring Boot 项目中,`application.yml` 文件用于配置日志。通过 `logging.config` 指定日志配置文件(如 `logback.xml`),实现日志详细设置。`logging.level` 可定义包的日志输出级别,例如将 `com.itcodai.course03.dao` 包设为 `trace` 级别,便于开发时查看 SQL 操作。日志级别从高到低为 ERROR、WARN、INFO、DEBUG,生产环境建议调整为较高级别以减少日志量。本课程采用 yml 格式,因其层次清晰,但需注意格式要求。
1122 0
|
7月前
|
人工智能 监控 安全
如何快速上手【Spring AOP】?核心应用实战(上篇)
哈喽大家好吖~欢迎来到Spring AOP系列教程的上篇 - 应用篇。在本篇,我们将专注于Spring AOP的实际应用,通过具体的代码示例和场景分析,帮助大家掌握AOP的使用方法和技巧。而在后续的下篇中,我们将深入探讨Spring AOP的实现原理和底层机制。 AOP(Aspect-Oriented Programming,面向切面编程)是Spring框架中的核心特性之一,它能够帮助我们解决横切关注点(如日志记录、性能统计、安全控制、事务管理等)的问题,提高代码的模块化程度和复用性。

热门文章

最新文章