当前位置: 首页 > 编程日记 > 正文

Spring3.0 AOP 具体解释

一、什么是 AOP。

AOP(Aspect Orient Programming),也就是面向切面编程。能够这样理解,面向对象编程(OOP)是从静态角度考虑程序结构,面向切面编程(AOP)是从动态角度考虑程序执行过程


二、AOP 的作用。

经常通过 AOP 来处理一些具有横切性质的系统性服务,如事物管理、安全检查、缓存、对象池管理等,AOP 已经成为一种很经常使用的解决方式。


三、AOP 的实现原理。

<img src="AOP代理.jpg" />

如图:AOP 实际上是由目标类的代理类实现的AOP 代理事实上是由 AOP 框架动态生成的一个对象,该对象可作为目标对象使用。AOP 代理包括了目标对象的所有方法,但 AOP 代理中的方法与目标对象的方法存在差异,AOP 方法在特定切入点加入了增强处理,并回调了目标对象的方法


四、Spring 中对 AOP 的支持

Spring 中 AOP 代理由 Spring 的 IoC 容器负责生成、管理,其依赖关系也由 IoC 容器负责管理。因此,AOP 代理能够直接使用容器中的其它 Bean 实例作为目标,这样的关系可由 IoC 容器的依赖注入提供。Spring 默认使用 Java 动态代理来创建 AOP 代理, 这样就能够为不论什么接口实例创建代理了。当须要代理的类不是代理接口的时候, Spring 自己主动会切换为使用 CGLIB 代理,也可强制使用 CGLIB。 

AOP 编程事实上是非常easy的事情。纵观 AOP 编程, 当中须要程序猿參与的仅仅有三个部分:

  • 定义普通业务组件。
  • 定义切入点,一个切入点可能横切多个业务组件。
  • 定义增强处理,增强处理就是在 AOP 框架为普通业务组件织入的处理动作。

所以进行 AOP 编程的关键就是定义切入点和定义增强处理。一旦定义了合适的切入点和增强处理,AOP 框架将会自己主动生成 AOP 代理,即:代理对象的方法 = 增强处理 + 被代理对象的方法


五、Spring 中 AOP 的实现。

Spring 有例如以下两种选择来定义切入点和增强处理。

  • 基于 Annotation 的“零配置”方式:使用@Aspect、@Pointcut等 Annotation 来标注切入点和增强处理。
  • 基于 XML 配置文件的管理方式:使用 Spring 配置文件来定义切入点和增强点。

1、基于 Annotation 的“零配置”方式。

(1)、首先启用 Spring 对 @AspectJ 切面配置的支持。

<?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/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/beans/spring-aop-3.0.xsd"><!-- 启动对@AspectJ注解的支持 --><aop:aspectj-autoproxy/>
</beans>

假设不打算使用 Spring 的 XML Schema 配置方式,则应该在 Spring 配置文件里添加例如以下片段来启用@AspectJ 支持。

<!-- 启用@AspectJ 支持 -->
<bean class="org.springframeword.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" />


(2)、定义切面 Bean。

当启动了@AspectJ 支持后,仅仅要在 Spring 容器中配置一个带@Aspect 凝视的 Bean, Spring 将会自己主动识别该 Bean 并作为切面处理。

// 使用@Aspect 定义一个切面类
@Aspect
public class LogAspect {// 定义该类的其它内容...
}

(3)、定义 Before 增强处理。

// 定义一个切面
@Aspect
public class BeforeAdviceTest {// 匹配 com.wicresoft.app.service.impl 包下全部类的全部方法作为切入点@Before("execution(* com.wicresoft.app.service.impl.*.*(..))")public void authorith(){System.out.println("模拟进行权限检查。");}
}

上面使用@Before Annotation 时,直接指定了切入点表达式,指定匹配 com.wicresoft.app.service.impl包下全部类的全部方法运行作为切入点。
关于这个表达式的规则例如以下图。



(4)、定义 AfterReturning 增强处理。

// 定义一个切面
@Aspect
public class AfterReturningAdviceTest {// 匹配 com.wicresoft.app.service.impl 包下全部类的全部方法作为切入点@AfterReturning(returning="rvt", pointcut="execution(* com.wicresoft.app.service.impl.*.*(..))")public void log(Object rvt) {System.out.println("模拟目标方法返回值:" + rvt);System.out.println("模拟记录日志功能...");}
}

(5)、定义 AfterThrowing 增强处理。

// 定义一个切面
@Aspect
public class AfterThrowingAdviceTest {// 匹配 com.wicresoft.app.service.impl 包下全部类的全部方法作为切入点@AfterThrowing(throwing="ex", pointcut="execution(* com.wicresoft.app.service.impl.*.*(..))")public void doRecoverActions(Throwable ex) {System.out.println("目标方法中抛出的异常:" + ex);System.out.println("模拟抛出异常后的增强处理...");}
}

(6)、定义 After 增强处理。

After 增强处理与AfterReturning 增强处理有点相似,但也有差别:

  • AfterReturning 增强处理处理仅仅有在目标方法成功完毕后才会被织入。
  • After 增强处理无论目标方法怎样结束(保存成功完毕和遇到异常中止两种情况),它都会被织入。

// 定义一个切面
@Aspect
public class AfterAdviceTest {// 匹配 com.wicresoft.app.service.impl 包下全部类的全部方法作为切入点@After("execution(* com.wicresoft.app.service.impl.*.*(..))")public void release() {System.out.println("模拟方法结束后的释放资源...");}
}

(7)、Around 增强处理

Around 增强处理近似等于 Before 增强处理和  AfterReturning 增强处理的总和。它可改变运行目标方法的參数值,也可改变目标方法之后的返回值。

// 定义一个切面
@Aspect
public class AroundAdviceTest {// 匹配 com.wicresoft.app.service.impl 包下全部类的全部方法作为切入点@Around("execution(* com.wicresoft.app.service.impl.*.*(..))")public Object processTx(ProceedingJoinPoint jp) throws java.lang.Throwable {System.out.println("运行目标方法之前,模拟開始事物...");// 运行目标方法,并保存目标方法运行后的返回值Object rvt = jp.proceed(new String[]{"被改变的參数"});System.out.println("运行目标方法之前,模拟结束事物...");return rvt + "新增的内容";}
}

(8)、訪问目标方法的參数。

訪问目标方法最简单的做法是定义增强处理方法时将第一个參数定义为 JoinPoint 类型,当该增强处理方法被调用时,该 JoinPoint 參数就代表了织入增强处理的连接点。JoinPoint 里包括了例如以下几个经常用法。

  • Object[] getArgs(): 返回运行目标方法时的參数。
  • Signature getSignature(): 返回被增强的方法的相关信息。
  • Object getTarget(): 返回被织入增强处理的目标对象。
  • Object getThis(): 返回 AOP 框架为目标对象生成的代理对象。

提示当时使用 Around 处理时,我们须要将第一个參数定义为 ProceedingJoinPoint 类型,该类型是 JoinPoint 类型的子类


(9)、定义切入点。

所谓切入点,事实上质就是为一个切入点表达式起一个名称,从而同意在多个增强处理中重用该名称。

Spring 切入点定义包括两个部分:

  • 一个切入点表达式。
  • 一个包括名字和随意參数的方法签名。

// 使用@Pointcut Annotation 时指定切入点表达式
@pointcut("execution * transfer(..)")
// 使用一个返回值为void,方法体为空的方法来命名切入点
private void anyOldTransfer(){}// 使用上面定义的切入点
@AfterReturning(pointcut="anyOldTransfer()", returning="reVal")
public void writeLog(String msg, Object reVal){...
}

2、基于 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/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/beans/spring-aop-3.0.xsd"><aop:config><!-- 将 fourAdviceBean 转换成切面 Bean, 切面 Bean 的新名称为:fourAdviceAspect,指定该切面的优先级为2 --><aop:aspect id="fourAdviceAspect" ref="fourAdviceBean" order="2"><!-- 定义个After增强处理,直接指定切入点表达式,以切面 Bean 中的 Release() 方法作为增强处理方法 --><aop:after pointcut="execution(* com.wicresoft.app.service.impl.*.*(..))" method="release" /><!-- 定义个Before增强处理,直接指定切入点表达式,以切面 Bean 中的 authority() 方法作为增强处理方法 --><aop:before pointcut="execution(* com.wicresoft.app.service.impl.*.*(..))" method="authority" /><!-- 定义个AfterReturning增强处理,直接指定切入点表达式,以切面 Bean 中的 log() 方法作为增强处理方法 --><aop:after-returning pointcut="execution(* com.wicresoft.app.service.impl.*.*(..))" method="log" /><!-- 定义个Around增强处理,直接指定切入点表达式,以切面 Bean 中的 processTx() 方法作为增强处理方法 --><aop:around pointcut="execution(* com.wicresoft.app.service.impl.*.*(..))" method="processTx" /></aop:aspect></aop:config><!-- 省略各个Bean 的配置 --><!-- ... --></beans>

  • 配置切入点

<?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/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/beans/spring-aop-3.0.xsd"><aop:config><!-- 定义一个切入点,myPointcut,直接知道它相应的切入点表达式 --><aop:pointcut id="myPointcut" expression="execution(* com.wicresoft.app.service.impl.*.*(..))" method="release" /><aop:aspect id="afterThrowingAdviceAspect" ref="afterThrowingAdviceBean" order="1"><!-- 使用上面定于切入点定义增强处理 --><!-- 定义一个AfterThrowing 增强处理,指定切入点以切面 Bean 中的 doRecovertyActions() 方法作为增强处理方法 --><aop:after-throwing pointcut-ref="myPointcut" method="doRecovertyActions" throwing="ex" /></aop:aspect></aop:config><!-- 省略各个Bean 的配置 --><!-- ... --></beans>


參考:

《轻量级 Java EE 企业应用实战(第三版)》 李刚


转载于:https://www.cnblogs.com/mfrbuaa/p/3977689.html

相关文章:

通过Appium获取Android app中webview

因为要测试Android app中嵌入的web页面&#xff0c;所以需要从native切换到webview。网上查了好多帖子&#xff0c;都用到类似下面代码&#xff1a; //判断是否有 WEBVIEWSet<String> contextNames driver.getContextHandles();for (String contextName : contextNames)…

javascript原理_JavaScript程序包管理器工作原理简介

javascript原理by Shubheksha通过Shubheksha JavaScript程序包管理器工作原理简介 (An introduction to how JavaScript package managers work) A few days ago, ashley williams, one of the leaders of the Node.js community, tweeted this:几天前&#xff0c;Node.js社区…

iOS base64 MD5

网络APP 只要涉及用户隐私的数据&#xff0c;均不能以明文传输。 一 base64 编码 将任意的二进制数据转为编码为 65个字符的组成。 0-9 a-z A-Z / 一共 65 个 字符 例如&#xff1a; 1 mac 自带 base64命令 可以将base64 编码的文件可以转换 –》将桌面上1.png 图片经过…

【面试虐菜】—— Oracle知识整理《收获,不止Oracle》

普通堆表不足之处&#xff1a; 表更新有日志开销表删除有瑕疵表记录太大检索较慢索引回表读开销很大有序插入难有序读出DELETE产生的undo最多&#xff0c;redo也最多&#xff0c;因为undo也需要redo保护全局临时表&#xff1a;1 高效删除记录基于事务的全局临时表commit或者ses…

每日成长17年1月

2017年1月 1月9号 一、学习了ice ice是一个跨平台调用程序&#xff0c;与语言无关的一个中间件&#xff0c;比如&#xff0c;可以通过java的代码调用 c应用程序的接口。 1月11号 一.学习了 struts2 spring mybatis 的配置。 1.首先是web.xml的配置&#xff0c;主要配置两…

网络安全从事工作分类_那么,您想从事安全工作吗?

网络安全从事工作分类by Parisa Tabriz由Parisa Tabriz 那么&#xff0c;您想从事安全工作吗&#xff1f; (So, you want to work in security?) Every once in a while, I’ll get an email from an eager stranger asking for advice on how to have a career in security …

iOS 使用钥匙串将用户密码存入本地

在 iOS 开发中&#xff0c;用户一般注册时候&#xff0c;APP会将用户的用户名和密码直接保存到本地&#xff0c;便于用户下次直接进行登录。 这样就会牵扯到一个问题&#xff0c;用户的密码不能以明文的形式存储在本地&#xff0c;使用钥匙串进行保存用户的密码较为安全。 钥…

Leetcode: Sort List

Sort a linked list in O(n log n) time using constant space complexity. 记得Insert Sort List, 那个复杂度是O(N^2)的&#xff0c;这里要求O&#xff08;nlogn&#xff09;&#xff0c;所以想到merge sort, 需要用到Merge Two Sorted List的方法&#xff08;我写的merge函数…

[UT]Unit Test理解

Coding中有一个原则&#xff1a;Test Driven Development. UT中的一些基本概念&#xff1a; 1. 测试驱动 2. 测试桩 3. 测试覆盖 4. 覆盖率 单体测试内容&#xff1a; 1. 模块接口&#xff1a;测试模块的数据流 2. 局部数据结构&#xff1a;如变量名、初始化、类型转换等 3. 路…

gitter 卸载_最佳Gitter频道:VR和AR

gitter 卸载by Gitter通过吉特 最佳Gitter频道&#xff1a;VR和AR (Best Gitter channels on: VR & AR) Virtual reality is one of the biggest tech trends and a hot topic of 2016. Investment in that sector reached over 1 billion dollars early this year, while…

工作笔记---巡检记录

以下是工作中一些思路实现的笔记&#xff0c;业务需求是&#xff1a; 1、简易日历 2、质押物提交后的一天开始到当前系统时间之间才可以提交质押物 3、没有提交质押物的日期里面的图片以灰色图片站位&#xff0c;已经提交质押物的日期里面的图片以红色图片站位 4、图片点击之后…

大四狗找工作,持续更新

持续更新中....转载于:https://www.cnblogs.com/Wiki-ki/p/3979176.html

iOS8.0 之后指纹解锁

iOS 8.0 SDK 开放了调用指纹识别的API&#xff0c;但是仅限于支持5s 以后的机型 使用的话&#xff0c;很简单&#xff0c;要导入系统的库 #import <LocalAuthentication/LocalAuthentication.h> #import "ViewController.h" #import <LocalAuthenticatio…

gitter 卸载_最佳Gitter频道:Scala

gitter 卸载by Gitter通过吉特 最佳Gitter频道&#xff1a;Scala (Best Gitter channels on: Scala) Scala is an object-oriented functional language that has gained wide acceptance in developer communities for many of its merits. These include runtime performanc…

iOS AES加密

AES 美国国家安全局采用的加密方法&#xff0c;MAC 系统自带的钥匙串也是采用的AES 加密方法 有两种模式 CBC 模式 链式加密 &#xff0c;密码块链&#xff0c;使用一个秘钥和一个初始化向量&#xff0c;对数据执行加密。 ECB 电子密码本方法加密&#xff0c;数据拆分成块&a…

(转)Unity中武器与人物的碰撞检测

自&#xff1a;http://blog.csdn.net/Monzart7an/article/details/24435843 目前来说有三种思路&#xff0c;其实前两种算变种了&#xff1a; 1、动画关键帧回调 范围检测。 这个是在Asset store上面下的一个例子中看到的&#xff0c;其实之前在做端游时&#xff0c;也差不多是…

CentOS Linux解决 Device eth0 does not seem to be present

通过OVF部署Linux主机后提示 ringing up interface eth0: Device eth0 does not seem to be present,delaying initialization. 解决办法&#xff1a; 首先&#xff0c;打开/etc/udev/rules.d/70-persistent-net.rules内容如下面例子所示&#xff1a; # vi /etc/udev/rules.d/…

meteor从入门到精通_我已经大规模运行Meteor一年了。 这就是我所学到的。

meteor从入门到精通by Elie Steinbock埃莉斯坦博克(Elie Steinbock) 我已经大规模运行Meteor一年了。 这就是我所学到的。 (I’ve been running Meteor at scale for a year now. Here’s what I’ve learned.) A year ago I wrote an article describing my first experience…

使用javascript开发2048

嗯&#xff0c;团队队友开发了一个简单的2048...哈哈&#xff0c;没办法&#xff0c;这游戏那么疯狂&#xff0c;必须搞搞啦&#xff0c;大家能够直接粘贴代码到一个html文件&#xff0c;直接执行就可以 依赖文件&#xff1a;jquery&#xff0c;假设乜有&#xff0c;大家能够自…

html 自动弹出框

1.点击div外部隐藏&#xff0c; //*代表tip_box所包含的子元素 $(body).click(function(e) {var target $(e.target);if(!target.is(#tip_box *) ) {//事件处理} });2.div动态展开 .tip_box{width:300px;height:0;border-radius:3px;background-color:#fff;overflow:hidden;bo…

3-runtime 之 Tagged Pointer

Tagged Pointer 是自从iPhone 5s 之后引入的特性 1 先说一下iOS的内存布局 代码区&#xff1a;存放编译之后的代码数据段 &#xff1a;字符串常量 &#xff1a; NSString *hello “hello”;已经初始化和未初始化的全局变量&#xff0c;静态变量堆&#xff1a;通过alloc&#…

编程术语_伟大的编程术语烘烤

编程术语by Preethi Kasireddy通过Preethi Kasireddy 伟大的编程术语烘烤 (The Great Programming Jargon Bake-off) Imperative vs. Declarative. Pure vs. Impure. Static vs. Dynamic.命令式与声明式。 纯与不纯。 静态与动态。 Terminology like this is sprinkled throu…

Swift 圆环进度条

Swift 圆环进度条 import UICircularProgressRing import UIKit import UICircularProgressRing class ViewController: UIViewController {var progress:UICircularProgressRing!;override func viewDidLoad() {super.viewDidLoad()// Do any additional setup after loading …

Linux文件系统构成(第二版)

Linux文件系统构成/boot目录&#xff1a;内核文件、系统自举程序文件保存位置,存放了系统当前的内核【一般128M即可】如:引导文件grub的配置文件等/etc目录&#xff1a;系统常用的配置文件&#xff0c;所以备份系统时一定要备份此目录如&#xff1a;系统管理员经常需要修改的文…

include_once 问题

最近在做微信小程序&#xff0c;在include_once 微信文件后&#xff0c;该方法return 前面会用特殊字符&#xff0c;导致我return 给前端的本来是json串变成了字符 解决方法 &#xff1a; ob_clean(); return json_encode(array);转载于:https://www.cnblogs.com/zouzhe0/p/630…

babel6 babel7_当您已经准备好Babel时设置Flow

babel6 babel7by Jamie Kyle杰米凯尔(Jamie Kyle) 当您已经准备好Babel时设置Flow (Setting up Flow when you’ve already got Babel in place) Flow is a static type checker for JavaScript. It makes you more productive by providing feedback as you write code. Flow…

如何为Android上的产品设计一款合适的图标

如 果你已经完成了你的app&#xff0c;你一定会马上向其它人宣布这件事情。但是你需要注意一个很重要的问题&#xff0c;那就是app的图标。你的图标可能在项目启动之 前就已经设计好了&#xff0c;但我不喜欢这样&#xff0c;如果app没有完成实际上图标也没什么用了。如果你不是…

得到windows聚焦图片(windows 10)

有些Windows聚焦图片确实很漂亮&#xff0c;很希望保留下来&#xff0c;但是Windows聚焦图片总更好&#xff0c;网上有得到聚焦图片的方法&#xff0c;每次都手动去弄真麻烦&#xff0c;于是自己编了一个小程序&#xff0c;自动得到Windows聚焦图片&#xff0c;下面是运行这个小…

swift 加载gif 框架图片

swift 加载gif 框架图片 SwiftGifOrigin 以下代码 轻松搞定 let imgView UIImageView(frame: CGRect(x: 50, y: 100, width: 280, height: 200));imgView.loadGif(name: "gfff");self.view.addSubview(imgView);

devops_最低可行DevOps

devopsby Michael Shilman通过迈克尔希尔曼(Michael Shilman) 最低可行DevOps (Minimum Viable DevOps) 快速而肮脏的指南&#xff0c;用于扩展您的发布并拥抱互联网的死亡 (A quick and dirty guide to scaling your launch and embracing the Internet hug of death) Startu…