一、概念

1、理论

把横切关注点和业务逻辑相分离是面向切面编程所要解决的问题。如果要重用通用功能的话,最常见的面向对象技术是继承(inheritance)或 组成(delegation)。但是,如果在整个应用中都使用相同的基类,继承往往会导致一个脆弱的对象体系;而使用组成可能需要对委托对象进行复杂的调用。切面提供了取代继承和委托的另一种可选方案,而且在很多场景下更清晰简洁。Spring AOP 基于动态代理,所以Spring只支持方法连接点,这与一些其他的AOP框架是不同的,例如AspectJ和JBoss,除了方法切点,它们还提供了字段和构造器接入点。

2、AOP术语

横切关注点(cross-cutuing concern):散布在应用中多处的功能。

切面(aspect) : 横切关注点模块化为特殊的类。切面是通知和切点的结合。

通知(advice):定义了切面是什么以及何时使用。

Spring切面可以应用5种类型的通知:

前置通知(Before):在目标方法被调用之前调用通知功能;
后置通知(After):在目标方法完成之后调用通知,此时不会关心方法的输出是什么;
返回通知(After-returning):在目标方法成功执行之后调用通知;
异常通知(After-throwing):在目标方法抛出异常后调用通知;
环绕通知(Around):通知包裹了被通知的方法,在被通知的方法调用之前和调用之后执行自定义的行为。

切点(pointcut):定义了切面在何处调用,会匹配通知所要织入的一个或多个连接点。
连接点(join point):在应用执行过程中能够插入切面的一个点。这个点可以是调用方法时、抛出异常时、甚至修改一个字段时。

织入(Weaving):织入是把切面应用到目标对象并创建新的代理对象的过程。

织入有三种方式可以实现,Spring采用的是第三种,在运行期织入的:

编译期:切面在目标类编译时被织入。这种方式需要特殊的编译器。AspectJ的织入编译器就是以这种方式织入切面的。
类加载期:切面在目标类加载到JVM时被织入。这种方式需要特殊的类加载器(ClassLoader),它可以在目标类被引入应用之前增强该目标类的字节码。AspectJ 5的加载时织入(load-time weaving,LTW)就支持以这种方式织入切面。
运行期:切面在应用运行的某个时刻被织入。一般情况下,在织入切面时,AOP容器会为目标对象动态地创建一个代理对象。代理类封装了目标类,并拦截被通知方法的调用,再把调用转发给真正的目标bean。SpringAOP就是以这种方式织入切面的。

3、AspectJ的切点表达式语言

注意:只有execution指示器是实际执行匹配的,而其他的指示器都是用来限制匹配的。这说明execution指示器是我们在编写切点定义时最主要使用的指示器 。同时需要注意的是, 表达式之间允许用 &&(and)、||(or)、!(not) 来匹配复杂的被通知类。除了上面罗列的表达式外,Spring 还提供了一个Bean 表达式来匹配 Bean 的id,例如  execution(* com.service.Performance.perform(..)) && bean(performance)

@args的正确用法:自定义一个ElementType.TYPE的注解,这个注解用来修饰自定义类型(比如自己写的一个类),一个方法以这个自定义的类的实例为参数且只能有这唯一一参数,那这个方法在调用时会被匹配@args(自定义注解)的切面拦截。
@annotation的正确用法:在切面类上用@annotation加自定义注解就可以拦截使用这个注解的方法。比如匹配 @RequestMapping  注解的类  @annotation(org.springframework.web.bind.annotation.RequestMapping)

@target (cn.javass.spring.chapter6.Secure)  任何目标对象持有Secure注解的类方法;必须是在目标对象上声明这个注解,在接口上声明的对它不起作用。

二、使用注解创建切面

1、添加pom.xml依赖

        <dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.6.11</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.11</version>
</dependency>

2、定义切面

@Aspect //表示这是一个切面类
public class Audience { //使用简明的PointCut
@Pointcut("execution(* com.service.Performance.perform(..))")
public void performance(){} //前置通知 即 @Before("execution(* com.service.Performance.perform(..))")
@Before("performance()")
public void silenceCellPhones(){
System.out.println("Silencing cell phones");
}
//前置通知 即 @Before("execution(* com.service.Performance.perform(..))")
@Before("performance()")
public void takeSeats(){
System.out.println("Taking seats");
} //方法调用结束通知(并不是指返回值通知,即使是void的返回值,仍然会触发通知) 即 @AfterReturning("execution(* com.service.Performance.perform(..))")
@AfterReturning("performance()")
public void applause(){
System.out.println("CLAP CLAP CLAP!!!");
} //有异常抛出的时候通知,即 @AfterThrowing("execution(* com.service.Performance.perform(..))")
@AfterThrowing("performance()")
public void demandRefund(){
System.out.println("Demanding a refund");
}
}

3、启用AspectJ注解的自动代理

有两种方式可以启用AspectJ 注解的自动代理:

(1)在 Java 配置文件中显示配置

@Configuration
@EnableAspectJAutoProxy //启用Aop自动代理
public class JavaConfig {
@Bean
public Audience getAudience(){
return new Audience();
}
}

(2)在XML文件中配置

    <!--启用AspectJ自动代理-->
<aop:aspectj-autoproxy/>
<bean id="audience" class="com.aspect.Audience"/>

不管你是使用JavaConfig还是XML,AspectJ自动代理都会为使用@Aspect注解的bean创建一个代理,这个代理会围绕着所有该切面的切点所匹配的bean。当程序执行到连接点的时候,就会由代理转到切面触发相应的通知。

4、创建环绕通知

@Aspect
public class Audience3 { @Pointcut("execution(* com.service.Performance.perform(..))")
public void performance(){} @Around("performance()")
public void watchPerformance(ProceedingJoinPoint joinPoint) {
System.out.println("Silencing cell phones");
System.out.println("Taking seats");
try {
joinPoint.proceed();
System.out.println("CLAP CLAP CLAP!!!");
} catch (Throwable throwable) {
System.out.println("Demanding a refund");
throwable.printStackTrace();
}
}
}

注意 ProceedingJoinPoint 作为参数。这个对象是必须要有的,因为你要在通知中通过它来调用被通知的方法。当要将控制权交给被通知的方法时,它需要调用ProceedingJoinPoint的proceed()方法。

5、切面匹配输入参数

@Aspect
public class TrackCounter { private Map<Integer,Integer> trackCounts=new HashMap<Integer, Integer>(); //@Pointcut("execution(* com.service.CompactDisc.playTrack(int)) && args(trackNumber)") //带入输入参数
//@Pointcut("target(com.service.CompactDisc) && args(trackNumber)") // target 匹配目标对象(非AOP对象)为指定类型
//@Pointcut("within(com.service..*) && args(trackNumber)") //com.service 包以及子包下的所有方法都执行
//@Pointcut("within(com.service..CompactDisc+) && args(trackNumber)") //com.service 包的CompactDisc类型以及子类型
@Pointcut("this(com.service.CompactDisc) && args(trackNumber)") //匹配当前AOP代理对象类型,必须是类型全称,不支持通配符
public void trackPlayed(int trackNumber){} @Before("trackPlayed(trackNumber)")
public void countTrack(int trackNumber){
int playCount = getPlayCount(trackNumber);
trackCounts.put(trackNumber,playCount+1);
System.out.println(trackCounts.toString());
} public int getPlayCount(int trackNumber){
return trackCounts.containsKey(trackNumber) ? trackCounts.get(trackNumber) : 0;
}
}
 参数的配置可以用占位符 * 和 .. 
 * 的意思是任意类型任意名称的一个参数
 .. 的意思是任意类型,任意多个参数,并且只能放到args的后面。 

6、利用切面注入新功能

Java并不是动态语言。一旦类编译完成了,我们就很难为该类添加新的功能了。但是,我们的切面编程却可以做到动态的添加方法...话虽如此,其实也不过是障眼法罢了。实际上,面向切面编程,不过是把方法添加到切面代理中,当要对添加的方法调用的时候,可以把被通知的 Bean 转换成相应的接口。也就是代理会把此调用委托给实现了新接口的某个其他对象。实际上,一个bean的实现被拆分到了多个类中。(说实话,想了半天,实在想不到这个功能有什么作用......)

(1) 重新定义一个接口和实现类

public interface Encoreable {
void performEncode();
}
public class DefaultEncoreable implements Encoreable {

    public void performEncode() {
System.out.println("this is DefaultEncoreable");
}
}

(2) 把接口实现类嵌入到目标类代理中

@Aspect
public class EncoreableIntroducer { @DeclareParents(value = "com.service.CompactDisc+",
defaultImpl = DefaultEncoreable.class) //value 表示要嵌入哪些目标类的代理 。 defaultImpl:表示要嵌入的接口的默认实现方法
public static Encoreable encoreable;
}

(3) JUnit 测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class Test02 { @Autowired
private CompactDisc compactDisc; @Test
public void test02(){
compactDisc.playTrack(123);
Encoreable compactDisc = (Encoreable) this.compactDisc; //当要调用添加的新功能的时候,这个用法相当于由代理转换到对应类实现,不会报类型转换错误
compactDisc.performEncode(); }
}

三、使用XML声明切面

1、定义切面

public class AudienceXML {

    public void  silenceCellPhones(){
System.out.println("Silencing cell phones");
}
public void takeSeats(){
System.out.println("Taking seats");
}
public void applause(){
System.out.println("CLAP CLAP CLAP!!!");
}
public void demandRefund(){
System.out.println("Demanding a refund");
}
}

2、XML配置切面

    <aop:config>
<aop:aspect ref="audienceXML">
<aop:pointcut id="performance" expression="execution(* com.service.Performance.perform(..))"/>
<aop:before method="silenceCellPhones" pointcut-ref="performance"/>
<aop:before method="takeSeats" pointcut-ref="performance"/>
<aop:after-returning method="applause" pointcut-ref="performance"/>
<aop:after-throwing method="demandRefund" pointcut-ref="performance"/>
</aop:aspect>
</aop:config>

3、创建环绕通知

public class Audience3XML {

    public void watchPerformance(ProceedingJoinPoint joinPoint) {
System.out.println("Silencing cell phones");
System.out.println("Taking seats");
try {
joinPoint.proceed();
System.out.println("CLAP CLAP CLAP!!!");
} catch (Throwable throwable) {
System.out.println("Demanding a refund");
throwable.printStackTrace();
}
}
}
    <aop:config>
<aop:aspect ref="audience3XML">
<aop:pointcut id="performance3" expression="execution(* com.service.Performance.perform(..))"/>
<aop:around method="watchPerformance" pointcut-ref="performance3"/>
</aop:aspect>
</aop:config>

4、匹配输入参数

    <aop:config>
<aop:aspect ref="trackCounter">
<aop:pointcut id="trackPlayed" expression="execution(* com.service.CompactDisc.playTrack(int)) and args(trackNumber)"/>
<aop:before method="countTrack" pointcut-ref="trackPlayed"/>
</aop:aspect>
</aop:config>

5、注入新功能

    <aop:config>
<aop:aspect>
<aop:declare-parents types-matching="com.service.CompactDisc+"
implement-interface="com.service.Encoreable"
default-impl="com.service.impl.DefaultEncoreable"
delegate-ref="encoreableDelegate"/> </aop:aspect>
</aop:config>

再学习之Spring(面向切面编程)的更多相关文章

  1. 快速高效掌握企业级项目中的Spring面向切面编程应用,外带讲面试技巧

    Spring面向切面编程(AOP)是企业级应用的基石,可以这样说,如果大家要升级到高级程序员,这部分的知识必不可少. 这里我们将结合一些具体的案例来讲述这部分的知识,并且还将给出AOP部分的一些常见面 ...

  2. Spring 面向切面编程(AOP)

    Spring 系列教程 Spring 框架介绍 Spring 框架模块 Spring开发环境搭建(Eclipse) 创建一个简单的Spring应用 Spring 控制反转容器(Inversion of ...

  3. Spring学习笔记:面向切面编程AOP(Aspect Oriented Programming)

    一.面向切面编程AOP 目标:让我们可以“专心做事”,避免繁杂重复的功能编码 原理:将复杂的需求分解出不同方面,将公共功能集中解决 *****所谓面向切面编程,是一种通过预编译方式和运行期动态代理实现 ...

  4. spring框架学习(三)——AOP( 面向切面编程)

    AOP 即 Aspect Oriented Program 面向切面编程 首先,在面向切面编程的思想里面,把功能分为核心业务功能,和周边功能. 所谓的核心业务,比如登陆,增加数据,删除数据都叫核心业务 ...

  5. 详解Spring面向切面编程(AOP)三种实现

    一.什么是AOP AOP(Aspect Oriented Programming),即面向切面编程,可以说是OOP(Object Oriented Programming,面向对象编程)的补充和完善. ...

  6. Spring——面向切面编程(AOP)详解

    声明:本博客仅仅是一个初学者的学习记录.心得总结,其中肯定有许多错误,不具有参考价值,欢迎大佬指正,谢谢!想和我交流.一起学习.一起进步的朋友可以加我微信Liu__66666666 这是简单学习一遍之 ...

  7. Spring面向切面编程(AOP)

    1 spring容器中bean特性 Spring容器的javabean对象默认是单例的. 通过在xml文件中,配置可以使用某些对象为多列. Spring容器中的javabean对象默认是立即加载(立即 ...

  8. Spring面向切面编程(AOP,Aspect Oriented Programming)

    AOP为Aspect Oriented Programming的缩写,意为:面向切面编程(也叫面向方面),可以通过预编译方式和运行期动态代理实现在不修改源代码的情况下给程序动态统一添加功能的一种技术. ...

  9. Spring面向切面编程

    在使用面向切面编程时,我们可以在一个地方定义通用的共鞥,但是可以通过声明的方式定义这个功能要以何种方式在何处应用,而无需修改受影响的类.横切关注点可以被模块化为特殊的类,这些类被称为切面.这样的优点是 ...

随机推荐

  1. D - MUH and Cube Walls

    D. MUH and Cube Walls   Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant ...

  2. EasyUI实现购物车、菜单和窗口栏等最常用的用户界面功能

    一.EasyUI jQuery EasyUI 是一个基于 jQuery 的框架,集成了各种用户界面插件. easyui 提供建立现代化的具有交互性的 javascript 应用的必要的功能. 使用 e ...

  3. Node.js 常用工具

    Node.js 常用工具 util 是一个Node.js 核心模块,提供常用函数的集合,用于弥补核心JavaScript 的功能 过于精简的不足. util.inherits util.inherit ...

  4. 玩转 HTML5 下 WebGL 的 3D 模型交并补

    建设性的立体几何具有许多实际用途,它用于需要简单几何对象的情况下,或者数学精度很重要的地方,几乎所有的工程 CAD 软件包都使用 CSG(可以用于表示刀具切削,以及零件必须配合在一起的特征).CSG ...

  5. day3--深入学习命令总结

    1.查看命令帮助的几种方法 a.[命令] --help   适用于一般命令,非内置命令 b.man  [命令]     适用于一般命令,非内置命令 c.help  [命令]     适用于内置命令 d ...

  6. Magicodes.Admin.Core开源框架总体介绍

    框架说明 Magicodes.Admin.Core框架在ABP以及ASP.NET ZERO的基础上进行了封装和完善,目前基于.NET Core 2.0+(Framework版本),由于部分组件在.NE ...

  7. 【机器学习实战】第15章 大数据与MapReduce

    第15章 大数据与MapReduce 大数据 概述 大数据: 收集到的数据已经远远超出了我们的处理能力. 大数据 场景 假如你为一家网络购物商店工作,很多用户访问该网站,其中有些人会购买商品,有些人则 ...

  8. 让C++控制台程序停下来,实现暂停功能

    一.针对Microsoft #include   <stdlib.h> (1)第一种方式system( "PAUSE "); --------------------  ...

  9. 你应该学会的Postman用法

    postman这个神器相信大家都用过,程序员作为非专业的测试人员,非常需要这么一款简单轻量级的restful测试工具,但是不知道你是否知道,postman的强大之处不只是测试一下接口,还有其他非常赞的 ...

  10. python线程池实现多线程

    参考文献 http://www.open-open.com/news/view/1c0179b http://blog.jobbole.com/52060/ 按照这个博客,实现获取多台服务器的空间使用 ...