回顾
在上一篇搞懂AOP之一,拦截器链中,我们介绍了MethodInterceptor增强目标类的方式,了解到了AOP的拦截器是如何使用,以及多个拦截器组成的拦截器链是如何工作的,并且看到了如何使用ProxyFactory去创建代理类。本篇接上篇,接着介绍另外一种增强方式–引入增强。
了解引入增强
定义
spring中的引入增强对应IntroductionInterceptor类。看下spring对其的定义:
/**
* Subinterface of AOP Alliance MethodInterceptor that allows additional interfaces
* to be implemented by the interceptor, and available via a proxy using that
* interceptor. This is a fundamental AOP concept called <b>introduction</b>.
*
* <p>Introductions are often <b>mixins</b>, enabling the building of composite
* objects that can achieve many of the goals of multiple inheritance in Java.
*
* @author Rod Johnson
* @see DynamicIntroductionAdvice
*/
public interface IntroductionInterceptor extends MethodInterceptor, DynamicIntroductionAdvice {
}
MethodInterceptor的子接口,允许添加由拦截器实现接口,并可以通过代理使用拦截器。这是AOP的基本概念。
从字面意思理解比较懵,下文将通过实例去理解。
我只是一个翻译官,对于源码的英文注释,我会保留并贴出来。因为我觉得编程这玩意,有时候翻译过来味道就变了,作者原本的思想可能就失真了,所以还是建议多读注释,spring的注释字字珍贵,没什么废话。
AOP是一种思想,而非实现。AOP是基于OOP,而又远远高于OOP,主要是将主要核心业务和交叉业务分离,交叉业务就是切面。introduction是AOP中的一个基本概念。不要把AOP和spring绑定起来,也不要把introduction和spring绑定起来。
相关类
在spring AOP中,与引入增强有关的类主要有:IntroductionInterceptor、DynamicIntroductionAdvice、DelegatingIntroductionInterceptor、IntroductionInfoSupport和IntroductionInfo。先总览下他们之间的关系,后文将一一介绍。
IntroductionInterceptor和MethodInterceptor
IntroductionInterceptor和MethodInterceptor相比有什么区别呢?
我的理解是,MethodInterceptor是对目标类方法的增强,它是基于目标类方法,在目标类方法基础上添加额外的逻辑。而IntroductionInterceptor是在不修改目标类的情况下,可以让没有实现A接口的目标类,具备A接口的功能,是凭空赋予目标类新的能力。这就好比,MethodInterceptor可以让一个篮球水平如周琦的人变得像姚明一样(非黑),而IntroductionInterceptor可以赋予一个不会打篮球的人运球、投篮的能力。这就是“0到1(从无到有)”和“1到2(从有到富)”的区别。
引用增强的原理
使用
学会一个东西之前,要先知道怎么用它。
还是以搞懂AOP之一,拦截器链中的例子,我们新建一个目标类Cat,实现了Animal接口。
public class Cat implements Animal {
@Override
public void bark() {
System.out.println("miao miao miao...");
}
}
###################
public interface Animal {
void bark();
}
接下来我们新建一个接口Flyable,定义了“飞行”的行为。
public interface Flyable {
void fly();
}
同时,定义引入飞行的增强行为,FlyableIntroductionInterceptor:
public class FlyableIntroductionInterceptor extends DelegatingIntroductionInterceptor implements Flyable {
@Override
public void fly() {
System.out.println("fly fly fly...");
}
}
FlyableIntroductionInterceptor继承了DelegatingIntroductionInterceptor,实现了Flyable接口,定义了fly的具体实现,这里仅仅打印一些东西。
接下来我们就在不修改Cat的前提下,让Cat也具有Flyable的行为。
public static void main(String[] args) {
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.addAdvice(new LogInterceptor());
proxyFactory.addAdvice(new TimeInterceptor());
proxyFactory.addAdv