分类: 【java】2013-12-10 18:53 724人阅读 评论(0) 收藏 举报
1.简介
Spring 中的AOP为Aspect Oriented Programming的缩写,面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。以下是Spring AOP的小例子
2.例子简介
2.1切面aspect:Logging.java
  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. public void beforeAdvice(){
  16. System.out.println("Logging:before... ");
  17. }
  18. public void afterAdvice(){
  19. System.out.println("Logging:after... ");
  20. }
  21. /**
  22. *
  23. * @param retVal 函数的返回值
  24. */
  25. public void afterReturningAdvice(Object retVal){
  26. if(retVal==null){
  27. return;
  28. }
  29. System.out.println("Logging:return :"+retVal.toString());
  30. }
  31. public void afterThrowingAdvice(IllegalArgumentException ex){
  32. System.out.println("Logging:exception:"+ex.toString());
  33. }
  34. }
2.2Bean: Student.java
  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文件配置
  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测试
  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. import org.springframework.context.ApplicationContext;
  9. import org.springframework.context.support.ClassPathXmlApplicationContext;
  10. /*
  11. *@author: ZhengHaibo
  12. *web:     http://blog.csdn.net/nuptboyzhb
  13. *mail:    zhb931706659@126.com
  14. *2013-12-10  Nanjing,njupt,China
  15. */
  16. public class TestMain {
  17. /**
  18. * @param args
  19. */
  20. public static void main(String[] args) {
  21. // TODO Auto-generated method stub
  22. ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
  23. Student student = (Student)context.getBean("student");
  24. System.out.println("-------------");
  25. student.getId();
  26. System.out.println("-------------");
  27. student.getName();
  28. System.out.println("-------------");
  29. student.print("Hi,I am a student");
  30. System.out.println("-------------");
  31. try{
  32. student.printThrowException();
  33. }catch (Exception e) {
  34. // TODO: handle exception
  35. System.out.println(e.getMessage());
  36. }
  37. }
  38. }

2.5运行结果:

  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)

  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. import org.aspectj.lang.JoinPoint;
  9. /*
  10. *@author: ZhengHaibo
  11. *web:     http://blog.csdn.net/nuptboyzhb
  12. *mail:    zhb931706659@126.com
  13. *2013-12-10  Nanjing,njupt,China
  14. */
  15. public class Logging {
  16. public void beforeAdvice(JoinPoint jointPoint){
  17. Object methodArgs[] = jointPoint.getArgs();//获取切入点函数的参数
  18. for(Object arg:methodArgs){
  19. System.out.println("Logging:args type="+arg.getClass().getName());
  20. System.out.println("Logging:args value="+arg);
  21. }
  22. System.out.println("Logging:ClassName="+jointPoint.getTarget().getClass().getName());
  23. System.out.println("Logging:MethodName="+jointPoint.getSignature().getName());
  24. System.out.println("Logging:before... ");
  25. }
  26. public void afterAdvice(){
  27. System.out.println("Logging:after... ");
  28. }
  29. /**
  30. *
  31. * @param retVal 函数的返回值
  32. */
  33. public void afterReturningAdvice(Object retVal){
  34. if(retVal==null){
  35. return;
  36. }
  37. System.out.println("Logging:return :"+retVal.toString());
  38. }
  39. public void afterThrowingAdvice(IllegalArgumentException ex){
  40. System.out.println("Logging:exception:"+ex.toString());
  41. }
  42. }

此时的运行结果为:

 
  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...
未经允许,不得用于商业目的

SSH框架系列:Spring AOP应用记录日志Demo的更多相关文章

  1. Maven环境下搭建SSH框架之Spring整合Hibernate

    © 版权声明:本文为博主原创文章,转载请注明出处 1.搭建环境 Spring:4.3.8.RELEASE Hibernate:5.1.7.Final MySQL:5.7.17 注意:其他版本在某些特性 ...

  2. Spring框架系列之AOP思想

    微信公众号:compassblog 欢迎关注.转发,互相学习,共同进步! 有任何问题,请后台留言联系! 1.AOP概述 (1).什么是 AOP AOP 为 Aspect Oriented Progra ...

  3. SSH框架系列:Spring配置多个数据源

    分类: [java]2013-12-09 16:59 1247人阅读 评论(0) 收藏 举报 1.问题的引入 对于普通的SSH框架而言,一般配置一个数据源,一个SessionFactory,一个事务管 ...

  4. SSH框架系列:Spring读取配置文件以及获取Spring注入的Bean

    分类: [java]2013-12-09 16:29 1020人阅读 评论(0) 收藏 举报 1.简介 在SSH框架下,假设我们将配置文件放在项目的src/datasource.properties路 ...

  5. Eclipse搭建SSH框架(Struts2+Spring+Hibernate)

    见识少的我经过一天多的研究才知道,在MyEclipse中搭好的框架的配置文件和jar包是通用的.接下来——亮剑! 工具:Eclipse+Tomcat+Mysql 一.先在Eclipse中配置好Tomc ...

  6. java框架篇---spring AOP 实现原理

    什么是AOP AOP(Aspect-OrientedProgramming,面向方面编程),可以说是OOP(Object-Oriented Programing,面向对象编程)的补充和完善.OOP引入 ...

  7. SSH框架中spring的原理

    在ssh项目中,是有明确分工的,spring的作用就相当于将struts和hibernate连接起来,是将两个没有关系的框架的特性,方法,action都放在spring的配置文件中使他们建立关系.取他 ...

  8. Spring AOP应用实例demo

    AOP(Aspect-Oriented Programming.面向方面编程).能够说是OOP(Object-OrientedPrograming.面向对象编程)的补充和完好.OOP引入封装.继承和多 ...

  9. SSH框架实现仿淘宝购物demo

    还记得六月份实习的时候,曾经做过一个电商的项目,项目里面需要实现类似淘宝购物车的移动端的demo,随着项目的进行,再一次跟购物车碰面,但是今天呢,不是移动端的需求,如何使用SSH框架实现类似淘宝的购物 ...

随机推荐

  1. Hibernate学习(五)

    自关联测试案例 1.创建表 drop table if exists t_category ; create table t_category ( id ) primary key , name ) ...

  2. 吴裕雄--天生自然Numpy库学习笔记:NumPy 创建数组

    import numpy as np x = np.empty([3,2], dtype = int) print (x) import numpy as np # 默认为浮点数 x = np.zer ...

  3. 【转载】Linux截图工具

    如果linux安装了gnome,那么系统自带了一款截屏软件 gnome-screenshot,使用起来很方便,功能齐备,支持命令行.简单介绍如下. 功能 对屏幕,窗口,或自定义的区域进行截图. 选项 ...

  4. jQuery结合CSS实现手风琴组件(2)----利用seajs实现静态资源模块化引入

    1. 目录结构(webStrom) 2. 代码 1.html <!DOCTYPE html> <html lang="en"> <head> & ...

  5. Java面向对象编程 -3

    this关键字 this可以算是Java里面比较复杂的关键字,因为this的使用形式约定了它的灵活性,在程序里面,使用this可以实现以下三类结构的描述: 当前类中的属性:this属性; 当前类中的方 ...

  6. 一大波新款iPhone跟安卓厂商抢夺5G市场

    据外媒最新报道称,苹果已经基本完成了今年iPhone的推新阵容,其发布的多款新机中,将涵盖399美元-1149美元的售价区间,特别是5G手机,起步价可能会很亲民,其目的在于进一步占据市场. 今年苹果将 ...

  7. jquery 判定checkbox是否选中

    CheckBox 判定是否选中 使用 attr('checked')来做判别是不行的,除非所有的选中取消都是使用这个属性来处理. 正确的做法是使用 .prop('checked') 来判定.

  8. Go语言学习笔记(三)

    一.浮点数 1.概述 浮点类型用于存储带有小数点的数字 一个整数数值可以赋值给浮点类型但是一个整型变量不可以赋值给浮点类型 浮点数进行运算的结果是浮点数 Go语言中浮点类型有两个 float32 fl ...

  9. windows破解wifi小技巧

    1,首先使用手机某软件破解wifi,手机连上破解的wifi 2,在手机上打开下面界面 3,在电脑上使用二维码识别小工具扫描二维码 4,得到扫面结果 4,得到扫描结果 WIFI:T:WPA;S:DFZJ ...

  10. java.util.ConcurrentModificationException 异常原因和解决方法

    不要在 foreach 循环里进行元素的 remove/add 操作.remove 元素请使用 Iterator方式,如果并发操作,需要对 Iterator 对象加锁. 注意: 1.foreach遍历 ...