相关阅读

  • Spring AOP基础组件 Pointcut
  • Spring AOP基础组件 Advice
  • Spring AOP基础组件 Advisor

简介

表示被通知的标记接口;
实现子类主要是代理生成的对象和AdvisedSupport

源码

public interface Advised extends TargetClassAware {// Advice配置信是否支持修改boolean isFrozen();// 是否代理指定的类而不是接口boolean isProxyTargetClass();// 获取代理的接口Class<?>[] getProxiedInterfaces();// 判断指定接口是否被代理boolean isInterfaceProxied(Class<?> intf);// 设置代理的目标对象void setTargetSource(TargetSource targetSource);/ 获取代理的目标对象TargetSource getTargetSource();// 设置是否暴露代理对象到ThreadLocal,方便通过AopContext获取代理对象void setExposeProxy(boolean exposeProxy);// 判断是否暴露代理对象boolean isExposeProxy();// 设置是否已预过滤,如果已预过滤,则持有的Advisors都适用void setPreFiltered(boolean preFiltered);// 判断是否已预过滤boolean isPreFiltered();// 获取AdvisorsAdvisor[] getAdvisors();// 获取Advisors数量default int getAdvisorCount() {return getAdvisors().length;}// 添加Advisor到链尾void addAdvisor(Advisor advisor) throws AopConfigException;// 添加Advisor到指定位置,pos必须有效void addAdvisor(int pos, Advisor advisor) throws AopConfigException;// 移除指定Advisorboolean removeAdvisor(Advisor advisor);// 移除指定位置的Advisorvoid removeAdvisor(int index) throws AopConfigException;// 获取指定Advisor的位置int indexOf(Advisor advisor);// 替换指定Advisor,如果旧Advisor是引介Advisor,则需要重新获取代理,否则新旧接口都不支持boolean replaceAdvisor(Advisor a, Advisor b) throws AopConfigException;// 添加Advice到链尾void addAdvice(Advice advice) throws AopConfigException;// 添加Advice到指定位置,pos必须有效void addAdvice(int pos, Advice advice) throws AopConfigException;// 移除指定Adviceboolean removeAdvice(Advice advice);// 获取指定Advice的位置int indexOf(Advice advice);// 获取String形式的ProxyConfigString toProxyConfigString();
}

实现子类

public interface Advised extends TargetClassAwarepublic class AdvisedSupport extends ProxyConfig implements Advisedpublic class ProxyCreatorSupport extends AdvisedSupportpublic class ProxyFactoryBean extends ProxyCreatorSupport implements FactoryBean<Object>, BeanClassLoaderAware, BeanFactoryAwarepublic class ProxyFactory extends ProxyCreatorSupportpublic class AspectJProxyFactory extends ProxyCreatorSupport

AdvisedSupport

简介

AOP代理配置管理类的基础类,这些管理类本身不是AOP代理类,但是它们的子类通常是直接获取AOP代理的工厂类;
AdvisedSupport实现了AdviceAdvisor的管理,子类需要负责创建代理;

核心代码

public class AdvisedSupport extends ProxyConfig implements Advised {/*** Canonical TargetSource when there's no target, and behavior is* supplied by the advisors.*/// 目标对象的典例public static final TargetSource EMPTY_TARGET_SOURCE = EmptyTargetSource.INSTANCE;// 目标对象TargetSource targetSource = EMPTY_TARGET_SOURCE;// 预过滤标识private boolean preFiltered = false;// Advisor链工厂AdvisorChainFactory advisorChainFactory = new DefaultAdvisorChainFactory();// 方法缓存,以Method为Key,Advisor chain list为Valueprivate transient Map<MethodCacheKey, List<Object>> methodCache;// 代理实现的接口集合private List<Class<?>> interfaces = new ArrayList<>();// Advisor集合private List<Advisor> advisors = new ArrayList<>();public AdvisedSupport() {this.methodCache = new ConcurrentHashMap<>(32);}public AdvisedSupport(Class<?>... interfaces) {this();setInterfaces(interfaces);}public void setTarget(Object target) {setTargetSource(new SingletonTargetSource(target));}@Overridepublic void setTargetSource(@Nullable TargetSource targetSource) {this.targetSource = (targetSource != null ? targetSource : EMPTY_TARGET_SOURCE);}@Overridepublic TargetSource getTargetSource() {return this.targetSource;}public void setTargetClass(@Nullable Class<?> targetClass) {this.targetSource = EmptyTargetSource.forClass(targetClass);}@Override@Nullablepublic Class<?> getTargetClass() {return this.targetSource.getTargetClass();}@Overridepublic void setPreFiltered(boolean preFiltered) {this.preFiltered = preFiltered;}@Overridepublic boolean isPreFiltered() {return this.preFiltered;}public void setAdvisorChainFactory(AdvisorChainFactory advisorChainFactory) {// 校验AdvisorChainFactoryAssert.notNull(advisorChainFactory, "AdvisorChainFactory must not be null");this.advisorChainFactory = advisorChainFactory;}public AdvisorChainFactory getAdvisorChainFactory() {return this.advisorChainFactory;}public void setInterfaces(Class<?>... interfaces) {// 校验代理的接口集合Assert.notNull(interfaces, "Interfaces must not be null");this.interfaces.clear();for (Class<?> ifc : interfaces) {addInterface(ifc);}}public void addInterface(Class<?> intf) {Assert.notNull(intf, "Interface must not be null");if (!intf.isInterface()) {// 只支持接口类型throw new IllegalArgumentException("[" + intf.getName() + "] is not an interface");}if (!this.interfaces.contains(intf)) {this.interfaces.add(intf);adviceChanged();}}public boolean removeInterface(Class<?> intf) {return this.interfaces.remove(intf);}@Overridepublic Class<?>[] getProxiedInterfaces() {return ClassUtils.toClassArray(this.interfaces);}@Overridepublic boolean isInterfaceProxied(Class<?> intf) {// 遍历代理的接口集合for (Class<?> proxyIntf : this.interfaces) {// 判断指定的接口类型是否属于遍历接口if (intf.isAssignableFrom(proxyIntf)) {return true;}}return false;}@Overridepublic final Advisor[] getAdvisors() {return this.advisors.toArray(new Advisor[0]);}@Overridepublic int getAdvisorCount() {return this.advisors.size();}@Overridepublic void addAdvisor(Advisor advisor) {int pos = this.advisors.size();addAdvisor(pos, advisor);}@Overridepublic void addAdvisor(int pos, Advisor advisor) throws AopConfigException {if (advisor instanceof IntroductionAdvisor) {// 校验IntroductionAdvisorvalidateIntroductionAdvisor((IntroductionAdvisor) advisor);}addAdvisorInternal(pos, advisor);}@Overridepublic boolean removeAdvisor(Advisor advisor) {int index = indexOf(advisor);if (index == -1) {return false;}else {removeAdvisor(index);return true;}}@Overridepublic void removeAdvisor(int index) throws AopConfigException {if (isFrozen()) {// 不支持变动throw new AopConfigException("Cannot remove Advisor: Configuration is frozen.");}if (index < 0 || index > this.advisors.size() - 1) {throw new AopConfigException("Advisor index " + index + " is out of bounds: " +"This configuration only has " + this.advisors.size() + " advisors.");}Advisor advisor = this.advisors.remove(index);if (advisor instanceof IntroductionAdvisor) {IntroductionAdvisor ia = (IntroductionAdvisor) advisor;// 移除IntroductionAdvisor相关的接口for (Class<?> ifc : ia.getInterfaces()) {removeInterface(ifc);}}adviceChanged();}@Overridepublic int indexOf(Advisor advisor) {Assert.notNull(advisor, "Advisor must not be null");return this.advisors.indexOf(advisor);}@Overridepublic boolean replaceAdvisor(Advisor a, Advisor b) throws AopConfigException {Assert.notNull(a, "Advisor a must not be null");Assert.notNull(b, "Advisor b must not be null");int index = indexOf(a);if (index == -1) {return false;}removeAdvisor(index);addAdvisor(index, b);return true;}public void addAdvisors(Advisor... advisors) {addAdvisors(Arrays.asList(advisors));}public void addAdvisors(Collection<Advisor> advisors) {if (isFrozen()) {// 不支持变动throw new AopConfigException("Cannot add advisor: Configuration is frozen.");}if (!CollectionUtils.isEmpty(advisors)) {for (Advisor advisor : advisors) {if (advisor instanceof IntroductionAdvisor) {validateIntroductionAdvisor((IntroductionAdvisor) advisor);}Assert.notNull(advisor, "Advisor must not be null");this.advisors.add(advisor);}adviceChanged();}}private void validateIntroductionAdvisor(IntroductionAdvisor advisor) {advisor.validateInterfaces();// If the advisor passed validation, we can make the change.Class<?>[] ifcs = advisor.getInterfaces();for (Class<?> ifc : ifcs) {addInterface(ifc);}}private void addAdvisorInternal(int pos, Advisor advisor) throws AopConfigException {Assert.notNull(advisor, "Advisor must not be null");if (isFrozen()) {// 不支持变动throw new AopConfigException("Cannot add advisor: Configuration is frozen.");}if (pos > this.advisors.size()) {throw new IllegalArgumentException("Illegal position " + pos + " in advisor list with size " + this.advisors.size());}this.advisors.add(pos, advisor);adviceChanged();}protected final List<Advisor> getAdvisorsInternal() {return this.advisors;}@Overridepublic void addAdvice(Advice advice) throws AopConfigException {int pos = this.advisors.size();addAdvice(pos, advice);}@Overridepublic void addAdvice(int pos, Advice advice) throws AopConfigException {Assert.notNull(advice, "Advice must not be null");// 将Advice包装为Advisorif (advice instanceof IntroductionInfo) {// We don't need an IntroductionAdvisor for this kind of introduction:// It's fully self-describing.addAdvisor(pos, new DefaultIntroductionAdvisor(advice, (IntroductionInfo) advice));}else if (advice instanceof DynamicIntroductionAdvice) {// We need an IntroductionAdvisor for this kind of introduction.throw new AopConfigException("DynamicIntroductionAdvice may only be added as part of IntroductionAdvisor");}else {addAdvisor(pos, new DefaultPointcutAdvisor(advice));}}@Overridepublic boolean removeAdvice(Advice advice) throws AopConfigException {int index = indexOf(advice);if (index == -1) {return false;}else {removeAdvisor(index);return true;}}@Overridepublic int indexOf(Advice advice) {Assert.notNull(advice, "Advice must not be null");for (int i = 0; i < this.advisors.size(); i++) {Advisor advisor = this.advisors.get(i);if (advisor.getAdvice() == advice) {return i;}}return -1;}protected void adviceChanged() {// 清除方法缓存this.methodCache.clear();}// Method的简单包装类,作为methodCache的Keyprivate static final class MethodCacheKey implements Comparable<MethodCacheKey> {private final Method method;private final int hashCode;public MethodCacheKey(Method method) {this.method = method;this.hashCode = method.hashCode();}@Overridepublic int compareTo(MethodCacheKey other) {// 先比较方法名称int result = this.method.getName().compareTo(other.method.getName());if (result == 0) {// 再比较方法签名result = this.method.toString().compareTo(other.method.toString());}return result;}}
}

ProxyCreatorSupport

简介

代理工厂的基础类,提供对可配置的AopProxyFactory的便捷访问;

核心代码

public class ProxyCreatorSupport extends AdvisedSupport {private AopProxyFactory aopProxyFactory;private final List<AdvisedSupportListener> listeners = new ArrayList<>();// 初始状态未激活,当创建第一个代理对象时设置为trueprivate boolean active = false;public ProxyCreatorSupport() {this.aopProxyFactory = new DefaultAopProxyFactory();}public ProxyCreatorSupport(AopProxyFactory aopProxyFactory) {Assert.notNull(aopProxyFactory, "AopProxyFactory must not be null");this.aopProxyFactory = aopProxyFactory;}protected final synchronized AopProxy createAopProxy() {if (!this.active) {activate();}// 通过AopProxyFactory创建代理对象return getAopProxyFactory().createAopProxy(this);}private void activate() {this.active = true;// 通知激活for (AdvisedSupportListener listener : this.listeners) {listener.activated(this);}}@Overrideprotected void adviceChanged() {super.adviceChanged();synchronized (this) {if (this.active) {// 通知变动for (AdvisedSupportListener listener : this.listeners) {listener.adviceChanged(this);}}}}protected final synchronized boolean isActive() {return this.active;}
}

ProxyFactory

简介

支持自定义获取和配置AOP代理实例的代理实例工厂;

核心代码

public class ProxyFactory extends ProxyCreatorSupport {public Object getProxy() {// 使用默认地ClassLoader创建代理对象return createAopProxy().getProxy();}public Object getProxy(@Nullable ClassLoader classLoader) {// 使用指定的ClassLoader创建代理对象return createAopProxy().getProxy(classLoader);}// 根据指定的接口和拦截器创建代理对象@SuppressWarnings("unchecked")public static <T> T getProxy(Class<T> proxyInterface, Interceptor interceptor) {return (T) new ProxyFactory(proxyInterface, interceptor).getProxy();}// 根据指定的接口和目标对象创建代理对象@SuppressWarnings("unchecked")public static <T> T getProxy(Class<T> proxyInterface, TargetSource targetSource) {return (T) new ProxyFactory(proxyInterface, targetSource).getProxy();}// 创建继承自目标对象类型的代理对象public static Object getProxy(TargetSource targetSource) {if (targetSource.getTargetClass() == null) {throw new IllegalArgumentException("Cannot create class proxy for TargetSource with null target class");}ProxyFactory proxyFactory = new ProxyFactory();proxyFactory.setTargetSource(targetSource);proxyFactory.setProxyTargetClass(true);return proxyFactory.getProxy();}
}

ProxyFactoryBean

简介

基于Spring BeanFactory中的Bean来创建AOP代理实例的FactoryBean的实现;
AdvisorAdvice都是通过bean name指定,最后一个bean name可能是目标对象,但通常目标对象都是通过targetName/target/targetSource属性指定(一旦指定,那么所有bean name只能是Advisor或者Advice);

核心代码

public class ProxyFactoryBean extends ProxyCreatorSupportimplements FactoryBean<Object>, BeanClassLoaderAware, BeanFactoryAware {@Override@Nullablepublic Object getObject() throws BeansException {initializeAdvisorChain();if (isSingleton()) {// 单例则会缓存return getSingletonInstance();}else {if (this.targetName == null) {logger.info("Using non-singleton proxies with singleton targets is often undesirable. " +"Enable prototype proxies by setting the 'targetName' property.");}// 多例则每次创建新实例return newPrototypeInstance();}}private synchronized Object getSingletonInstance() {if (this.singletonInstance == null) {this.targetSource = freshTargetSource();// 自动检测代理的接口if (this.autodetectInterfaces && getProxiedInterfaces().length == 0 && !isProxyTargetClass()) {// Rely on AOP infrastructure to tell us what interfaces to proxy.Class<?> targetClass = getTargetClass();if (targetClass == null) {throw new FactoryBeanNotInitializedException("Cannot determine target class for proxy");}// 设置代理的接口setInterfaces(ClassUtils.getAllInterfacesForClass(targetClass, this.proxyClassLoader));}// Initialize the shared singleton instance.super.setFrozen(this.freezeProxy);// 创建代理对象this.singletonInstance = getProxy(createAopProxy());}return this.singletonInstance;}private synchronized Object newPrototypeInstance() {// 通过当前配置的拷贝创建代理对象ProxyCreatorSupport copy = new ProxyCreatorSupport(getAopProxyFactory());TargetSource targetSource = freshTargetSource();copy.copyConfigurationFrom(this, targetSource, freshAdvisorChain());if (this.autodetectInterfaces && getProxiedInterfaces().length == 0 && !isProxyTargetClass()) {// Rely on AOP infrastructure to tell us what interfaces to proxy.Class<?> targetClass = targetSource.getTargetClass();if (targetClass != null) {copy.setInterfaces(ClassUtils.getAllInterfacesForClass(targetClass, this.proxyClassLoader));}}copy.setFrozen(this.freezeProxy);// 创建代理对象return getProxy(copy.createAopProxy());}protected Object getProxy(AopProxy aopProxy) {return aopProxy.getProxy(this.proxyClassLoader);}@Overrideprotected void adviceChanged() {super.adviceChanged();if (this.singleton) {logger.debug("Advice has changed; re-caching singleton instance");synchronized (this) {// 清除缓存的单例this.singletonInstance = null;}}}
}

AspectJProxyFactory

简介

基于AspectJ的代理工厂,支持创建持有AspectJ切面的代理对象;

核心代码

public class AspectJProxyFactory extends ProxyCreatorSupport {public void addAspect(Object aspectInstance) {Class<?> aspectClass = aspectInstance.getClass();String aspectName = aspectClass.getName();AspectMetadata am = createAspectMetadata(aspectClass, aspectName);if (am.getAjType().getPerClause().getKind() != PerClauseKind.SINGLETON) {throw new IllegalArgumentException("Aspect class [" + aspectClass.getName() + "] does not define a singleton aspect");}addAdvisorsFromAspectInstanceFactory(new SingletonMetadataAwareAspectInstanceFactory(aspectInstance, aspectName));}public void addAspect(Class<?> aspectClass) {String aspectName = aspectClass.getName();AspectMetadata am = createAspectMetadata(aspectClass, aspectName);MetadataAwareAspectInstanceFactory instanceFactory = createAspectInstanceFactory(am, aspectClass, aspectName);addAdvisorsFromAspectInstanceFactory(instanceFactory);}private void addAdvisorsFromAspectInstanceFactory(MetadataAwareAspectInstanceFactory instanceFactory) {List<Advisor> advisors = this.aspectFactory.getAdvisors(instanceFactory);Class<?> targetClass = getTargetClass();Assert.state(targetClass != null, "Unresolvable target class");advisors = AopUtils.findAdvisorsThatCanApply(advisors, targetClass);AspectJProxyUtils.makeAdvisorChainAspectJCapableIfNecessary(advisors);AnnotationAwareOrderComparator.sort(advisors);addAdvisors(advisors);}private AspectMetadata createAspectMetadata(Class<?> aspectClass, String aspectName) {AspectMetadata am = new AspectMetadata(aspectClass, aspectName);if (!am.getAjType().isAspect()) {throw new IllegalArgumentException("Class [" + aspectClass.getName() + "] is not a valid aspect type");}return am;}private MetadataAwareAspectInstanceFactory createAspectInstanceFactory(AspectMetadata am, Class<?> aspectClass, String aspectName) {MetadataAwareAspectInstanceFactory instanceFactory;if (am.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) {// Create a shared aspect instance.Object instance = getSingletonAspectInstance(aspectClass);instanceFactory = new SingletonMetadataAwareAspectInstanceFactory(instance, aspectName);}else {// Create a factory for independent aspect instances.instanceFactory = new SimpleMetadataAwareAspectInstanceFactory(aspectClass, aspectName);}return instanceFactory;}private Object getSingletonAspectInstance(Class<?> aspectClass) {return aspectCache.computeIfAbsent(aspectClass,clazz -> new SimpleAspectInstanceFactory(clazz).getAspectInstance());}@SuppressWarnings("unchecked")public <T> T getProxy() {return (T) createAopProxy().getProxy();}@SuppressWarnings("unchecked")public <T> T getProxy(ClassLoader classLoader) {return (T) createAopProxy().getProxy(classLoader);}
}

Spring AOP基础组件 Advised相关推荐

  1. Spring AOP基础组件 Pointcut

    相关阅读 Spring AOP基础组件 Advice Spring AOP基础组件 Advisor 简介 定义了切面的匹配点,即哪些类的哪些方法:在Spring AOP中匹配点主要是class(Cla ...

  2. Spring AOP基础组件 Advisor

    相关阅读 Spring AOP基础组件 Pointcut Spring AOP基础组件 Advice 简介 持有AOP Advice和决定Advice适用性的过滤器(比如Pointcut)的基础接口: ...

  3. Spring AOP基础组件 Joinpoint

    相关阅读 Spring AOP基础组件 Pointcut Spring AOP基础组件 Advice Spring AOP基础组件 AopProxy 简介 Joinpoint表示通用的运行时连接点: ...

  4. 了解动态代理:Spring AOP基础

    为什么选择AOP: 要了解AOP(面向方面​​的编程),我们需要了解软件开发中的"横切关注点". 在每个项目中,都有一定数量的代码在多个类,多个模块中重复执行,例如几乎所有类和所有 ...

  5. SSM框架笔记10:Spring AOP基础

    Spring AOP基础   AOP:Aspect-Oriented Programming 面向切面编程.   Spring的AOP作用在于解耦.AOP让一组类共享相同的行为(比如事务管理.日志管理 ...

  6. 【小家Spring】Spring AOP各个组件概述与总结【Pointcut、Advice、Advisor、Advised、TargetSource、AdvisorChainFactory...】

    每篇一句 基础技术总是枯燥但有价值的.数学.算法.网络.存储等基础技术吃得越透,越容易服务上层的各种衍生技术或产品 相关阅读 [小家Spring]Spring AOP原理使用的基础类打点(AopInf ...

  7. Spring Aop基础使用

    说到Spring,想必大家一定就马上想到了,哦Spring不就是帮助管理Bean对象,封装数据源,提供事务管理的东西么.的确,平常在使用Spring的时候,用到最多的就是Spring提供的这些功能了, ...

  8. Spring框架学习笔记05:Spring AOP基础

    文章目录 一.Spring AOP (一)AOP基本含义 (二)AOP基本作用 (三)AOP与OOP (四)AOP使用方式 (五)AOP基本概念 任务:骑士执行任务前和执行任务后,游吟诗人唱赞歌 (一 ...

  9. Spring AOP基础—JDK动态代理

    JDK动态代理主要涉及到java.lang.reflect包中的两个类:Proxy和InvocationHandler.其中InvocationHandler动态创建一个符合某一接口的实例,生成目标类 ...

  10. Spring Aop 组件概述

    Spring Aop 概述 AOP(Aspect-Oriented Programming) 面向切面编程, 这种编程模型是在 OOP(Object-Oriented Programming) 的基础 ...

最新文章

  1. “CRISPR婴儿”计划疯狂重启 顶级科学家们表示无力阻止
  2. Converting KVM VirtualHost To VMware vSphere VirtualHost
  3. struts2 中文件的位置问题
  4. 前端学习(2306):react之组件使用之图片使用
  5. python实现简易工资管理系统(Salary Manage)源码
  6. 卸载VMware Server后,无法加载登录用户界面 #F#
  7. easyui蛋疼之二 tabs与accordion
  8. html css回顾总结
  9. sql执行遇到汉字会停止执行吗_(数据)产品经理应该学会的SQL优化和进阶技巧...
  10. 【转载保存】Ubuntu14.04安装pycharm用于Python开发环境部署,并且支持pycharm使用中文输入
  11. PLC通过PIO模式控制绝对位置型IAI电缸
  12. win7连接远程服务器特别慢,主编告诉你win7远程桌面连接速度慢的完全解决教程...
  13. 复联3观影指南丨漫威宇宙里的AI黑科技
  14. 智能家居的新想法(2022)
  15. 折叠面板(Collapse)
  16. 央企招聘:中储粮集团2023公开招聘公告(校招+社招,共700人)
  17. 炸裂了!3分钟用GPT4做一个PPT!
  18. 暑期实训项目(2)--推特爬虫数据处理
  19. ctfshow摆烂杯
  20. java计算机毕业设计小型酒店管理系统源码+系统+数据库+lw文档+mybatis+运行部署

热门文章

  1. 基于Android Tv制作一个Tv桌面(三)
  2. AEMDA: Inferring miRNA-disease associations based on deep autoencoder
  3. PS网页设计教程XXII——在PS中创建单页复古网页布局
  4. 机器学习 识别图片人物动作_一键学习人物识别说明
  5. (四)SGE 常用命令
  6. HDU1814 求2-sat字典序最小的解
  7. 快速实现M5311NBIOT MQTT通信
  8. ICCV 2015 B-CNN细粒度分类
  9. [IOS]Presenting modal in iOS 13 fullscreen
  10. JS学习之路系列总结五行阵(此文犹如武林之中的易筋经,是你驰骋IT界的武功心法,学会JS五大阵法就学会了JS,博主建议先学三才阵)...