原文地址:http://www.cnblogs.com/dingyingsi/p/3323502.html

Spring的AOP可以通过对@AspectJ注解的支持和在XML中配置来实现,本文通过实例简述如何在Spring中使用AspectJ.Spring AOP AspectJ

一:使用AspectJ注解:
1,启用对AspectJ的支持:
通过在Spring的配置中引入下列元素来启用Spring对AspectJ的支持:
<aop:aspectj-autoproxy />
或者(如果不是使用XSD的话)
<bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" />
2,声明一个带有@Aspect注解的类,在这个类中声明那些方法需要被'关注'(利用@Pointcut),在那些时机点进行关注(利用@Before,@AfterReturning等等...),执行'切入'的方法
3,在Spring的配置文件中定义这个'切面'类:任意带有一个@Aspect切面(拥有@Aspect注解)的bean都将被Spring自动识别并用于配置在Spring AOP.
4,使用被Spring管理的bean,在执行被'关注'的方法时,'切入'的方法就会被执行.
一个完整的例子:
需要被'切入'的类:

public class Monkey {public void stealPeaches(String name) {System.out.println(" Monkey " + name + " is stealling peaches...");}public void stealCorns(String name) {System.out.println(" Monkey " + name + " is stealling corns...");}
}

'切面'类:

@Aspect
public class Guardian {@Pointcut("execution(* com.test.spring.aspectj.Monkey.stealPeaches(..))")public void guardOrchard() {}@Before(value = "guardOrchard()")public void guardOrchardBefore() {System.out.println("Guardian spotted a monkey is approaching the orchard...");}@AfterReturning("guardOrchard() && args(name,..)")public void guardOrchardAfter(String name) {System.out.println("Guardian caught a monkey stealling peaches whoes name is " + name + "...");}@Around("guardOrchard() && args(name,..)")
  public void guardOrchardAround(ProceedingJoinPoint joinpoint,String name) {
    System.out.println("Guardian guardOrchardAround started ... " + name);
    try {      joinpoint.proceed();
    } catch (Throwable e) {
      System.out.println("Guardian guardOrchardAround exception happened ... " + name);
    }    System.out.println("Guardian guardOrchardAround completed ... " + name);
  }    @Pointcut("execution(* com.test.spring.aspectj.Monkey.stealCorns(..))")public void guardFarm() {}@Before(value = "guardFarm()")public void guardFarmBefore() {System.out.println("Guardian spotted a monkey is approaching the farm...");}@AfterReturning("guardFarm() && args(name,..)")public void guardFarmAfter(String name) {System.out.println("Guardian caught a monkey stealling corns whoes name is " + name + "...");}
}

配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="    http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    http://www.springframework.org/schema/aop    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"><!--<aop:aspectj-autoproxy /> equals to <beanclass="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"/>--><aop:aspectj-autoproxy /><bean id="guardian" class="com.test.spring.aspectj.Guardian" /><bean id="monkey" class="com.test.spring.aspectj.Monkey" /></beans>

使用bean:

ApplicationContext context = new ClassPathXmlApplicationContext("conf/aspectJAppcontext.xml");Monkey monkey = (Monkey) context.getBean("monkey");try {monkey.stealPeaches("mighty monkey");monkey.stealCorns("mighty monkey");} catch (Exception e) {}

运行结果:

Guardian spotted a monkey is approaching the orchard...
Guardian guardOrchardAround started ... mighty monkey
Monkey mighty monkey is stealling peaches...
Guardian caught a monkey stealling peaches whoes name is mighty monkey...
Guardian guardOrchardAround completed ... mighty monkey
Guardian spotted a monkey is approaching the farm...Monkey mighty monkey is stealling corns...
Guardian caught a monkey stealling corns whoes name is mighty monkey...

二:通过XML配置AspectJ实现AOP:在java类中定义要被'方面'调用的切入方法,在XML中配置.
例子:被'切入'的类,普通java类:

public class Monkey {public void stealPeaches(String name) {System.out.println(" Monkey " + name + " is stealling peaches...");}public void stealCorns(String name,int numberToSteal) {System.out.println(" Monkey " + name + " is stealling corns...");}
}

定义要被'方面'调用的切入方法的类:

public class XMLGuardian {public void guardOrchardBefore() {System.out.println("XMLGuardian spotted a monkey is approaching the orchard...");}public void guardOrchardAfter() {System.out.println("XMLGuardian caught a monkey stealling peaches whoes name is ...");}public void guardFarmBefore() {System.out.println("XMLGuardian spotted a monkey is approaching the farm...");}public void guardFarmAfter(String name,int num,Object retVal) {System.out.println("XMLGuardian caught a monkey stealling " + num + " corns whoes name is ..." + name );}
}

XML配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="    http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    http://www.springframework.org/schema/aop    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"><bean id="guardian" class="com.test.spring.aspectj.XMLGuardian" /><bean id="monkey" class="com.test.spring.aspectj.Monkey" /><aop:config><aop:aspect id="myAspect" ref="guardian"><aop:pointcut id="guardOrchard"expression="execution(* com.test.spring.aspectj.Monkey.stealPeaches(..))" /><aop:before pointcut-ref="guardOrchard" method="guardOrchardBefore" /><aop:after-returning pointcut-ref="guardOrchard" method="guardOrchardAfter"/><aop:pointcut id="guardFarm"expression="execution(* com.test.spring.aspectj.Monkey.stealCorns(..))" /><aop:before pointcut-ref="guardFarm" method="guardFarmBefore" /><aop:after-returning pointcut="execution(* com.test.spring.aspectj.Monkey.stealCorns(..)) and args(name,num,..)" returning="retVal"method="guardFarmAfter" /><!--  arg-names="name1" --></aop:aspect>       </aop:config>
</beans>

客户端测试代码:

ApplicationContext context = new ClassPathXmlApplicationContext("conf/xmlaspectJAppcontext.xml");Monkey monkey = (Monkey) context.getBean("monkey");try {monkey.stealPeaches("mighty monkey");monkey.stealCorns("mighty monkey",3);} catch (Exception e) {}

运行结果:

XMLGuardian spotted a monkey is approaching the orchard...Monkey mighty monkey is stealling peaches...
XMLGuardian caught a monkey stealling peaches whoes name is ...
XMLGuardian spotted a monkey is approaching the farm...Monkey mighty monkey is stealling corns...
XMLGuardian caught a monkey stealling 3 corns whoes name is ...mighty monkey

Spring AOP 只支持对bean的方法级的'切入',而且AOP的内部机制和AspectJ有所区别,Spring主要是通过动态代理来实现AOP,使用JDK的动态代理(如果被代理的bean是interface的话)或者CGLIB(如果如果被代理的bean不是interface的话).

Srping 中的AOP相关推荐

  1. 一文读懂Spring中的AOP机制

    一.前言 这一篇我们来说一下 Spring 中的 AOP 机制,为啥说完注解的原理然后又要说 AOP 机制呢? 1.标记日志打印的自定义注解 @Target({ElementType.METHOD}) ...

  2. 动态代理——》AOP —— Spring 中的 AOP||AOP 相关术语||学习 spring 中的 AOP 要明确的事

    AOP 概述 什么是 AOP       AOP:全称是 Aspect Oriented Programming 即:面向切面编程 AOP 的作用及优势 作用: 在程序运行期间,不修改源码对已有方法进 ...

  3. Spring Boot中使用AOP统一处理Web请求日志

    AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术.AOP是Spring框架中的一个重要内容,它通 ...

  4. 【springboot中使用aop的具体步骤和示例】

    1.依赖 <dependency><groupId>org.springframework.boot</groupId><artifactId>spri ...

  5. Spring中的AOP(三)——基于Annotation的配置方式(一)

    为什么80%的码农都做不了架构师?>>>    AspectJ允许使用注解用于定义切面.切入点和增强处理,而Spring框架则可以识别并根据这些注解来生成AOP代理.Spring只是 ...

  6. spring中的aop术语和细节

    Spring中AOP的细节 说明 我们学习spring的aop,就是通过配置的方式 AOP相关术语 Joinpoint(连接点): 所谓连接点是指那些被拦截到的点.在spring中,这些点指的是方法, ...

  7. 手动实现SPring中的AOP(1)

    Spring中的AOP是基于JDK的API动态的在内存中创建代理对象的.所以这里先介绍一些设计模式之----代理模式: a)         代理模式的定义:代理(Proxy)模式是一种提供对目标对象 ...

  8. .Net中的AOP系列之《方法执行前后——边界切面》

    返回<.Net中的AOP>系列学习总目录 本篇目录 边界切面 PostSharp方法边界 方法边界 VS 方法拦截 ASP.NET HttpModule边界 真实案例--检查是否为移动端用 ...

  9. 【转】在.Net中关于AOP的实现

    原文地址:http://www.uml.org.cn/net/201004213.asp 一.AOP实现初步 AOP将软件系统分为两个部分:核心关注点和横切关注点.核心关注点更多的是Domain Lo ...

最新文章

  1. 问题和任务包003.使用报告.数据可视化.PowerBI.微软的新武器
  2. Android学习记录:SQLite数据库、res中raw的文件调用
  3. ubuntu20.04的xfce4下面安装百度输入法linux版本
  4. Spring高级之注解@Bean详解(超详细)
  5. Matlab中的各种运算符的用法
  6. linuxamp;amp;shell学习(积累中。。。)
  7. 对Mac硬盘重新分区后如何恢复丢失的数据?
  8. ssm-学子商城-项目第八天
  9. 进销存excel_进销存管理系统excel模板
  10. minio更换端口启动
  11. [笔记] Codeforces#274 Riding in a Lift (479E) DP
  12. c++获取umg ue_[UE4][V4.10]C++中定义UMG widget变量时的头文件引用有关问题
  13. MySQL - java.sql.SQLException: Data truncated for column ‘xx‘ at row 1
  14. HDU 6148 Valley Numer (数位DP)题解
  15. 关于使用EasyExcel进行单元格合并的问题
  16. 荣誉加持,驭势科技近期斩获奖项回顾
  17. Java书写文字格斗游戏
  18. androidP 对反射的限制之黑名单机制
  19. 高手勿进!写给初中级程序员以及还在大学修炼的“准程序员”的成长秘籍
  20. ffmpeg学习 函数分析sws_scale

热门文章

  1. 据说vite还是有坑,不行,那就还用vue-cli吧,命令vue create gua12,记一下,可能过一个星期不看,又忘了
  2. ubuntu16.04解决耳机没有声音
  3. 日常所用的耳机接口定义
  4. 新书《Android安全技术揭秘与防范》终于出版了
  5. linux可执行文件剪裁
  6. Android RxJava生命周期管理解决方案整理
  7. ClassFormatException:Invalid byte tag in constant pool: 18
  8. 基于stm32的音乐喷泉设计
  9. win10定时关机c语言,小编为你win10系统通过命令实现定时关机的步骤
  10. 苏黎世联邦理工学院计算机硕士申请条件,苏黎世联邦理工学院研究生申请条件...