/**
* Interface supplying the information necessary to describe an introduction.
* 为描述一个introduction(引入)提供必要信息的接口。但是这个接口之定义了一个
* Class<?>[] getInterfaces()方法,看来 introduction 最主要的信息就是要引入的接口
*
* <p>{@link IntroductionAdvisor IntroductionAdvisors} must implement this
* interface. If an {@link org.aopalliance.aop.Advice} implements this,
* it may be used as an introduction without an {@link IntroductionAdvisor}.
* In this case, the advice is self-describing, providing not only the
* necessary behavior, but describing the interfaces it introduces.
* IntroductionAdvisor 必须实现这个接口,假如一个 Advice 实现了IntroductionInfo,
* 它就可以被当作一个没有 IntroductionAdvisor 的introduction来使用。在这种情况下
* 这个Advice是自我描述的,不仅提供了必要的行为,和描述了要引入的接口
*
* @author Rod Johnson
* @since 1.1.1
*/
public interface IntroductionInfo {
/**
* 返回这个Advisor 或者 Advice 引入的额外的接口
* 这里的额外接口指的是,Advisor和Advice 没有实现这些接口,但是要具有这些接口的能力
* Return the additional interfaces introduced by this Advisor or Advice.
* @return the introduced interfaces
*/
Class<?>[] getInterfaces();
}
/**
* Superinterface for advisors that perform one or more AOP <b>introductions</b>.
*
*
* <p>This interface cannot be implemented directly; subinterfaces must
* provide the advice type implementing the introduction.
*
* <p>Introduction is the implementation of additional interfaces
* (not implemented by a target) via AOP advice.
* 引入是target对象通过Aop实现的额外的接口,这些额外的接口指的是target没有
* 实现的一些接口
* 比如:target 实现了接口A 和 接口B,但是还想给 target 添加接口C 和 接口D 的功能,
* 接口C 和 接口D 就属于引入的接口
* @author Rod Johnson
* @since 04.04.2003
* @see IntroductionInterceptor
*/
public interface IntroductionAdvisor extends Advisor, IntroductionInfo {
/**
* Return the filter determining which target classes this introduction
* should apply to.
* 返回一个过滤器,这个过滤器用来决定这个 introduction 因该引用到哪些类上
*
* <p>This represents the class part of a pointcut. Note that method
* matching doesn't make sense to introductions.
* 这代表了切点的 class 部分。注意对于introduction来说,方法匹配不起作用
*
* @return the class filter
*/
ClassFilter getClassFilter();
/**
* Can the advised interfaces be implemented by the introduction advice?
* Invoked before adding an IntroductionAdvisor.
* 在IntroductionAdvisor被添加之前调用,用来校验 introduction 引入的接口
* 能不能被introduction advice实现
* @throws IllegalArgumentException if the advised interfaces can't be
* implemented by the introduction advice
*
*/
void validateInterfaces() throws IllegalArgumentException;
}
/**
* Simple {@link org.springframework.aop.IntroductionAdvisor} implementation
* that by default applies to any class.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @since 11.11.2003
*/
@SuppressWarnings("serial")
public class DefaultIntroductionAdvisor implements IntroductionAdvisor, ClassFilter, Ordered, Serializable {
private final Advice advice;
private final Set<Class<?>> interfaces = new LinkedHashSet<>();
private int order = Ordered.LOWEST_PRECEDENCE;
/**
* Create a DefaultIntroductionAdvisor for the given advice.
* @param advice the Advice to apply (may implement the
* {@link org.springframework.aop.IntroductionInfo} interface)
* @see #addInterface
*/
public DefaultIntroductionAdvisor(Advice advice) {
// 这里的Advice同时也实现了IntroductionInfo,说明这个Advice实例既提供了要引入的接口
// ,又具有根据本次请求的Method的,将请求转发到delegate的能力
// 比如说:DelegatingIntroductionInterceptor
this(advice, (advice instanceof IntroductionInfo ? (IntroductionInfo) advice : null));
}
/**
* Create a DefaultIntroductionAdvisor for the given advice.
* @param advice the Advice to apply
* @param introductionInfo the IntroductionInfo that describes
* the interface to introduce (may be {@code null})
*/
public DefaultIntroductionAdvisor(Advice advice, @Nullable IntroductionInfo introductionInfo) {
Assert.notNull(advice, "Advice must not be null");
// 这里传进来的 Advice 不是像PointcutAdvisor中的Advice那样,对目标对象的方法进行加强
// 主要的业务还是在代理的目标对象
// DefaultIntroductionAdvisor的Advice最终是要完成主要业务的,Advice持有能够解决
// 所引入的接口的问题的实例 Object delegate ,这个delegate本身实现了引入的接口,
// 当执行到执行链中的Introduction Advice时,这个Advice会先判断这次调用的Method方法
// 所属的Class是不是Introduction引入的接口,如果是就直接把这个调用准发到 delegate
// ,delegate实现了Introduction引入的接口,能够解决本次调用,解决完了,直接就返回了
// 不再将请求向后传递了
this.advice = advice;
if (introductionInfo != null) {
Class<?>[] introducedInterfaces = introductionInfo.getInterfaces();
if (introducedInterfaces.length == 0) {
throw new IllegalArgumentException(
"IntroductionInfo defines no interfaces to introduce: " + introductionInfo);
}
for (Class<?> ifc : introducedInterfaces) {
addInterface(ifc);
}
}
}
/**
* Create a DefaultIntroductionAdvisor for the given advice.
* @param advice the Advice to apply
* @param ifc the interface to introduce
*/
public DefaultIntroductionAdvisor(DynamicIntroductionAdvice advice, Class<?> ifc) {
Assert.notNull(advice, "Advice must not be null");
this.advice = advice;
addInterface(ifc);
}
/**
* Add the specified interface to the list of interfaces to introduce.
* 添加要引入的接口
* @param ifc the interface to introduce
*/
public void addInterface(Class<?> ifc) {
Assert.notNull(ifc, "Interface must not be null");
if (!ifc.isInterface()) {
throw new IllegalArgumentException("Specified class [" + ifc.getName() + "] must be an interface");
}
this.interfaces.add(ifc);
}
// 这里相当于实现了 IntroductionInfo 的public Class<?>[] getInterfaces();
// 当通过AdvisedSupport#addAdvisor(int,org.springframework.aop.Advisor)
// 方法添加 Advisor 的时候,判断如果添加的Advisor,是一个IntroductionAdvisor
// ,就会将调用IntroductionAdvisor.getInterfaces()获取所有引入的接口,添加到
// AdvisedSupport.interfaces中,AdvisedSupport.interfaces中放的都是生成的代理
// 对象需要实现的接口,之后实现了这些接口,后期生成的代理才能强转为这些接口进行调用
@Override
public Class<?>[] getInterfaces() {
return ClassUtils.toClassArray(this.interfaces);
}
@Override
public void validateInterfaces() throws IllegalArgumentException {
for (Class<?> ifc : this.interfaces) {
if (this.advice instanceof DynamicIntroductionAdvice &&
!((DynamicIntroductionAdvice) this.advice).implementsInterface(ifc)) {
throw new IllegalArgumentException("DynamicIntroductionAdvice [" + this.advice + "] " +
"does not implement interface [" + ifc.getName() + "] specified for introduction");
}
}
}
@Override
public Advice getAdvice() {
return this.advice;
}
@Override
public boolean isPerInstance() {
return true;
}
@Override
public ClassFilter getClassFilter() {
// 因为DefaultIntroductionAdvisor本来就实现了ClassFilter
// 返回this
return this;
}
@Override
public boolean matches(Class<?> clazz) {
// 因为DefaultIntroductionAdvisor实现了ClassFilter
// 所以必须实现 matches 方法,这里直接返回 true
// 表示所有的 Class 都能匹配成功
return true;
}
}
上面说了创建 DefaultIntroductionAdvisor 的时候,需要一个能根据本次调用的Method的,将调用转发到 delegate 的Advice,DelegatingIntroductionInterceptor 就是这样一个Advice,DelegatingIntroductionInterceptor通过继承IntroductionInfoSupport具有了校验一个Method是否属于被引入的某一个接口的能力,当然IntroductionInfoSupport校验是所用的接口数据也是DelegatingIntroductionInterceptor 通过 implementInterfacesOnObject(delegate) 传给它的
/**
* Convenient implementation of the
* {@link org.springframework.aop.IntroductionInterceptor} interface.
*
* <p>Subclasses merely need to extend this class and implement the interfaces
* to be introduced themselves. In this case the delegate is the subclass
* instance itself. Alternatively a separate delegate may implement the
* interface, and be set via the delegate bean property.
* 很少需要扩展这个类,并且子类实现要引入的所有接口,如果真是这种情况,子类自己就是delegate。
* 还有可选方案就是,用一个单独的 delegate 实现要引入的所有接口,然后通过构造方法或者setter
* 将单独的 delegate 设置给 delegate 属性
* <p>Delegates or subclasses may implement any number of interfaces.
* All interfaces except IntroductionInterceptor are picked up from
* the subclass or delegate by default.
*
* <p>The {@code suppressInterface} method can be used to suppress interfaces
* implemented by the delegate but which should not be introduced to the owning
* AOP proxy.
*
* <p>An instance of this class is serializable if the delegate is.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @since 16.11.2003
* @see #suppressInterface
* @see DelegatePerTargetObjectIntroductionInterceptor
*/
@SuppressWarnings("serial")
public class DelegatingIntroductionInterceptor extends IntroductionInfoSupport
implements IntroductionInterceptor {
/**
* Object that actually implements the interfaces.
* May be "this" if a subclass implements the introduced interfaces.
*/
@Nullable
private Object delegate;
/**
* Construct a new DelegatingIntroductionInterceptor, providing
* a delegate that implements the interfaces to be introduced.
* @param delegate the delegate that implements the introduced interfaces
*/
public DelegatingIntroductionInterceptor(Object delegate) {
// 这里是通过一个独立的delegate来实现要引入的所有接口
// 然后通过构造方法初始化 delegate 字段
init(delegate);
}
/**
* Construct a new DelegatingIntroductionInterceptor.
* The delegate will be the subclass, which must implement
* additional interfaces.
* 如果不传一个独立的 delegate,说明子类自己就是 delegate
* ,子类必须实现 要引入的所有接口
*/
protected DelegatingIntroductionInterceptor() {
init(this);
}
/**
* Both constructors use this init method, as it is impossible to pass
* a "this" reference from one constructor to another.
* @param delegate the delegate object
*/
private void init(Object delegate) {
Assert.notNull(delegate, "Delegate must not be null");
this.delegate = delegate;
// 这里会调用 IntroductionInfoSupport.implementInterfacesOnObject()
// 将 delegate 所实现的所有接口提出出来,并发布
implementInterfacesOnObject(delegate);
// We don't want to expose the control interface
suppressInterface(IntroductionInterceptor.class);
suppressInterface(DynamicIntroductionAdvice.class);
}
/**
* Subclasses may need to override this if they want to perform custom
* behaviour in around advice. However, subclasses should invoke this
* method, which handles introduced interfaces and forwarding to the target.
* 如果子类想执行以下自定义的行为,就需要重写这个方法,然而,子类需要通过调用
* super.invoke(mi)调用这个方法,这个方法可以处理引入的接口,并将调用转发到
* delegate
*/
@Override
@Nullable
public Object invoke(MethodInvocation mi) throws Throwable {
// 调用IntroductionInfoSupport.isMethodOnIntroducedInterface()是不是属于
// 被引入的接口之一
if (isMethodOnIntroducedInterface(mi)) {
// Using the following method rather than direct reflection, we
// get correct handling of InvocationTargetException
// if the introduced method throws an exception.
// 如果判断这个Method是属于被引入的某一个接口,说明delegate能解决问题
// 调用delegate的方法完成调用的任务
Object retVal = AopUtils.invokeJoinpointUsingReflection(this.delegate, mi.getMethod(), mi.getArguments());
// Massage return value if possible: if the delegate returned itself,
// we really want to return the proxy.
if (retVal == this.delegate && mi instanceof ProxyMethodInvocation) {
Object proxy = ((ProxyMethodInvocation) mi).getProxy();
if (mi.getMethod().getReturnType().isInstance(proxy)) {
retVal = proxy;
}
}
return retVal;
}
// 如果不属于被引入的任何一个接口,就掉过当前 MethodInterceptor
return doProceed(mi);
}
/**
* Proceed with the supplied {@link org.aopalliance.intercept.MethodInterceptor}.
* Subclasses can override this method to intercept method invocations on the
* target object which is useful when an introduction needs to monitor the object
* that it is introduced into. This method is <strong>never</strong> called for
* {@link MethodInvocation MethodInvocations} on the introduced interfaces.
*/
@Nullable
protected Object doProceed(MethodInvocation mi) throws Throwable {
// If we get here, just pass the invocation on.
return mi.proceed();
}
}
/**
* Support for implementations of {@link org.springframework.aop.IntroductionInfo}.
*
* <p>Allows subclasses to conveniently add all interfaces from a given object,
* and to suppress interfaces that should not be added. Also allows for querying
* all introduced interfaces.
*
* @author Rod Johnson
* @author Juergen Hoeller
*/
@SuppressWarnings("serial")
public class IntroductionInfoSupport implements IntroductionInfo, Serializable {
protected final Set<Class<?>> publishedInterfaces = new LinkedHashSet<>();
private transient Map<Method, Boolean> rememberedMethods = new ConcurrentHashMap<>(32);
/**
* Suppress the specified interface, which may have been autodetected
* due to the delegate implementing it. Call this method to exclude
* internal interfaces from being visible at the proxy level.
* <p>Does nothing if the interface is not implemented by the delegate.
* @param ifc the interface to suppress
*/
public void suppressInterface(Class<?> ifc) {
this.publishedInterfaces.remove(ifc);
}
// 返回子类中的 delegate 所实现的所有接口
// 用于校验本次调用的Method是不是属于 子类的 delegate 所实现的所有接口
// 之一
@Override
public Class<?>[] getInterfaces() {
return ClassUtils.toClassArray(this.publishedInterfaces);
}
/**
* 校验传入的接口是不是 发布的被引入的接口之一
* Check whether the specified interfaces is a published introduction interface.
* @param ifc the interface to check
* @return whether the interface is part of this introduction
*/
public boolean implementsInterface(Class<?> ifc) {
for (Class<?> pubIfc : this.publishedInterfaces) {
if (ifc.isInterface() && ifc.isAssignableFrom(pubIfc)) {
return true;
}
}
return false;
}
/**
* 发布 delegate 所实现的所有接口,子类中调用。delegate是子类传的
* Publish all interfaces that the given delegate implements at the proxy level.
* @param delegate the delegate object
*/
protected void implementInterfacesOnObject(Object delegate) {
this.publishedInterfaces.addAll(ClassUtils.getAllInterfacesAsSet(delegate));
}
/**
* 校验MethodInvocation实例中的Method对象是不是属于被引入的某一个接口
* Is this method on an introduced interface?
* @param mi the method invocation
* @return whether the invoked method is on an introduced interface
*/
protected final boolean isMethodOnIntroducedInterface(MethodInvocation mi) {
Boolean rememberedResult = this.rememberedMethods.get(mi.getMethod());
if (rememberedResult != null) {
return rememberedResult;
}
else {
// Work it out and cache it.
boolean result = implementsInterface(mi.getMethod().getDeclaringClass());
this.rememberedMethods.put(mi.getMethod(), result);
return result;
}
}
}
举两个例子:
例子一:
public interface CarService {
Integer addCar(Car car);
}
public interface AService {
public String serviceA(String param);
public String serviceAA(String param);
}
public interface BService {
public String serviceB(String param);
public String serviceBB(String param);
}
public class CarServiceImpl implements CarService, AService, BService {
@Override
public Integer addCar(Car car) {
System.out.println("add");
//int i = 1 / 0;
return 1000;
}
@Override
public String serviceA(String param) {
System.out.println("执行 CarServiceImpl.serviceA() 参数:" + param);
return "CarServiceImpl.serviceA() 处理过的 " + param;
}
@Override
public String serviceAA(String param) {
System.out.println("执行 CarServiceImpl.serviceAA() 参数:" + param);
return "CarServiceImpl.serviceAA() 处理过的 " + param;
}
@Override
public String serviceB(String param) {
System.out.println("执行 CarServiceImpl.serviceB() 参数:" + param);
return "CarServiceImpl.serviceB() 处理过的 " + param;
}
@Override
public String serviceBB(String param) {
System.out.println("执行 CarServiceImpl.serviceBB() 参数:" + param);
return "CarServiceImpl.serviceBB() 处理过的 " + param;
}
}
public class ProxyFactoryTest1 {
public static void main(String[] args) {
ProxyFactory proxyFactory = new ProxyFactory();
CarServiceImpl carServiceImpl = new CarServiceImpl();
DelegatingIntroductionInterceptor delegatingIntroductionInterceptor = new DelegatingIntroductionInterceptor(carServiceImpl);
IntroductionAdvisor introductionAdvisor = new DefaultIntroductionAdvisor(delegatingIntroductionInterceptor);
proxyFactory.addAdvisor(introductionAdvisor);
CarService carServiceProxy = (CarService) proxyFactory.getProxy();
Integer integer = carServiceProxy.addCar(new Car());
System.out.println(integer);
AService aServiceProxy = (AService) proxyFactory.getProxy();
String serviceA = aServiceProxy.serviceA("测试引入代理");
System.out.println(serviceA);
BService bServiceProxy = (BService) proxyFactory.getProxy();
String serviceBB = bServiceProxy.serviceBB("测试引入代理");
System.out.println(serviceBB);
}
}
运行结果:
add
1000
执行 CarServiceImpl.serviceA() 参数:测试引入代理
CarServiceImpl.serviceA() 处理过的 测试引入代理
执行 CarServiceImpl.serviceBB() 参数:测试引入代理
CarServiceImpl.serviceBB() 处理过的 测试引入代理
例子二:
public class CustomDelegatingIntroductionInterceptor extends DelegatingIntroductionInterceptor implements CarService,AService,BService {
@Override
public Integer addCar(Car car) {
System.out.println("执行 CustomDelegatingIntroductionInterceptor.add() 参数:" + JSON.toJSONString(car));
return 2000;
}
@Override
public String serviceA(String param) {
System.out.println("执行 CustomDelegatingIntroductionInterceptor.serviceA() 参数:" + param);
return "CustomDelegatingIntroductionInterceptor.serviceA() 处理过的 " + param;
}
@Override
public String serviceAA(String param) {
System.out.println("执行 CustomDelegatingIntroductionInterceptor.serviceAA() 参数:" + param);
return "CustomDelegatingIntroductionInterceptor.serviceAA() 处理过的 " + param;
}
@Override
public String serviceB(String param) {
System.out.println("执行 CustomDelegatingIntroductionInterceptor.serviceB() 参数:" + param);
return "CustomDelegatingIntroductionInterceptor.serviceB() 处理过的 " + param;
}
@Override
public String serviceBB(String param) {
System.out.println("执行 CustomDelegatingIntroductionInterceptor.serviceBB() 参数:" + param);
return "CustomDelegatingIntroductionInterceptor.serviceBB() 处理过的 " + param;
}
}
public class ProxyFactoryTest2 {
public static void main(String[] args) {
ProxyFactory proxyFactory = new ProxyFactory();
IntroductionAdvisor introductionAdvisor = new DefaultIntroductionAdvisor(new CustomDelegatingIntroductionInterceptor());
proxyFactory.addAdvisor(introductionAdvisor);
CarService carServiceProxy = (CarService) proxyFactory.getProxy();
Integer integer = carServiceProxy.addCar(new Car());
System.out.println(integer);
AService aServiceProxy = (AService) proxyFactory.getProxy();
String serviceA = aServiceProxy.serviceA("测试引入代理");
System.out.println(serviceA);
BService bServiceProxy = (BService) proxyFactory.getProxy();
String serviceBB = bServiceProxy.serviceBB("测试引入代理");
System.out.println(serviceBB);
}
}
执行结果:
执行 CustomDelegatingIntroductionInterceptor.add() 参数:{}
2000
执行 CustomDelegatingIntroductionInterceptor.serviceA() 参数:测试引入代理
CustomDelegatingIntroductionInterceptor.serviceA() 处理过的 测试引入代理
执行 CustomDelegatingIntroductionInterceptor.serviceBB() 参数:测试引入代理
CustomDelegatingIntroductionInterceptor.serviceBB() 处理过的 测试引入代理