当前位置: 首页 > news >正文

[spring6: AspectMetadata AspectInstanceFactory]-源码解析

AspectMetadata

AspectMetadata 类用于存储与 AspectJ 方面相关的元数据,特别是与 Spring AOP 集成时的 “per” 子句相关信息。它使用 AspectJ 5 的反射 API,支持多种 AspectJ 实例化模型,如 “singleton”、“pertarget” 和 “perthis”。

@SuppressWarnings("serial")
public class AspectMetadata implements Serializable {// Aspect 的名称,通常作为 Spring 的 bean 名称,决定多个通知之间的优先级private final String aspectName;// Aspect 类本身,提供反射所需的类信息。private final Class<?> aspectClass;// AspectJ 的反射类型,用于访问 AspectJ 特定的元数据。private transient AjType<?> ajType;// 与 AspectJ 的 "per" 子句相关的 Spring AOP 切点,决定了实例化模型(例如 singleton 或 pertarget)private final Pointcut perClausePointcut;public AspectMetadata(Class<?> aspectClass, String aspectName) {this.aspectName = aspectName;Class<?> currClass = aspectClass;AjType<?> ajType = null;while (currClass != Object.class) {AjType<?> ajTypeToCheck = AjTypeSystem.getAjType(currClass);if (ajTypeToCheck.isAspect()) {ajType = ajTypeToCheck;break;}currClass = currClass.getSuperclass();}if (ajType == null) {throw new IllegalArgumentException("Class '" + aspectClass.getName() + "' is not an @AspectJ aspect");}if (ajType.getDeclarePrecedence().length > 0) {throw new IllegalArgumentException("DeclarePrecedence not presently supported in Spring AOP");}this.aspectClass = ajType.getJavaClass();this.ajType = ajType;switch (this.ajType.getPerClause().getKind()) {case SINGLETON -> {this.perClausePointcut = Pointcut.TRUE;}case PERTARGET, PERTHIS -> {AspectJExpressionPointcut ajexp = new AspectJExpressionPointcut();ajexp.setLocation(aspectClass.getName());ajexp.setExpression(findPerClause(aspectClass));ajexp.setPointcutDeclarationScope(aspectClass);this.perClausePointcut = ajexp;}case PERTYPEWITHIN -> {// Works with a type patternthis.perClausePointcut = new ComposablePointcut(new TypePatternClassFilter(findPerClause(aspectClass)));}default -> throw new AopConfigException("PerClause " + ajType.getPerClause().getKind() + " not supported by Spring AOP for " + aspectClass);}}// 从 AspectJ 注解中提取 "per" 子句的内容private String findPerClause(Class<?> aspectClass) {Aspect ann = aspectClass.getAnnotation(Aspect.class);if (ann == null) {return "";}String value = ann.value();int beginIndex = value.indexOf('(');if (beginIndex < 0) {return "";}return value.substring(beginIndex + 1, value.length() - 1);}public boolean isPerThisOrPerTarget() {PerClauseKind kind = getAjType().getPerClause().getKind();return (kind == PerClauseKind.PERTARGET || kind == PerClauseKind.PERTHIS);}public boolean isPerTypeWithin() {PerClauseKind kind = getAjType().getPerClause().getKind();return (kind == PerClauseKind.PERTYPEWITHIN);}public boolean isLazilyInstantiated() {return (isPerThisOrPerTarget() || isPerTypeWithin());}private void readObject(ObjectInputStream inputStream) throws IOException, ClassNotFoundException {inputStream.defaultReadObject();this.ajType = AjTypeSystem.getAjType(this.aspectClass);}}

AspectInstanceFactory

AspectInstanceFactory 是一个接口,用于提供切面实例并允许指定类加载器,同时通过实现 Ordered 接口来控制切面执行的顺序。

public interface AspectInstanceFactory extends Ordered {Object getAspectInstance();@NullableClassLoader getAspectClassLoader();}

SimpleAspectInstanceFactory

SimpleAspectInstanceFactoryAspectInstanceFactory 的实现,每次调用 getAspectInstance() 时都会创建一个新的切面实例,并提供切面类加载器和顺序控制功能。

public class SimpleAspectInstanceFactory implements AspectInstanceFactory {private final Class<?> aspectClass;public SimpleAspectInstanceFactory(Class<?> aspectClass) {Assert.notNull(aspectClass, "Aspect class must not be null");this.aspectClass = aspectClass;}public final Class<?> getAspectClass() {return this.aspectClass;}@Overridepublic final Object getAspectInstance() {try {return ReflectionUtils.accessibleConstructor(this.aspectClass).newInstance();}catch (NoSuchMethodException ex) {throw new AopConfigException("No default constructor on aspect class: " + this.aspectClass.getName(), ex);}catch (InstantiationException ex) {throw new AopConfigException("Unable to instantiate aspect class: " + this.aspectClass.getName(), ex);}catch (IllegalAccessException ex) {throw new AopConfigException("Could not access aspect constructor: " + this.aspectClass.getName(), ex);}catch (InvocationTargetException ex) {throw new AopConfigException("Failed to invoke aspect constructor: " + this.aspectClass.getName(), ex.getTargetException());}}@Override@Nullablepublic ClassLoader getAspectClassLoader() {return this.aspectClass.getClassLoader();}@Overridepublic int getOrder() {return getOrderForAspectClass(this.aspectClass);}protected int getOrderForAspectClass(Class<?> aspectClass) {return Ordered.LOWEST_PRECEDENCE;}}

SingletonAspectInstanceFactory

SingletonAspectInstanceFactoryAspectInstanceFactory 的实现,它使用一个指定的单例对象,每次调用 getAspectInstance() 都返回相同的实例,同时支持类加载器和顺序控制功能。

@SuppressWarnings("serial")
public class SingletonAspectInstanceFactory implements AspectInstanceFactory, Serializable {private final Object aspectInstance;public SingletonAspectInstanceFactory(Object aspectInstance) {Assert.notNull(aspectInstance, "Aspect instance must not be null");this.aspectInstance = aspectInstance;}@Overridepublic final Object getAspectInstance() {return this.aspectInstance;}@Override@Nullablepublic ClassLoader getAspectClassLoader() {return this.aspectInstance.getClass().getClassLoader();}@Overridepublic int getOrder() {if (this.aspectInstance instanceof Ordered ordered) {return ordered.getOrder();}return getOrderForAspectClass(this.aspectInstance.getClass());}protected int getOrderForAspectClass(Class<?> aspectClass) {return Ordered.LOWEST_PRECEDENCE;}}

MetadataAwareAspectInstanceFactory

MetadataAwareAspectInstanceFactoryAspectInstanceFactory 的子接口,专门用于返回与 AspectJ 注解类相关的 AspectMetadata,并提供获取创建互斥锁的方法。

public interface MetadataAwareAspectInstanceFactory extends AspectInstanceFactory {AspectMetadata getAspectMetadata();@NullableObject getAspectCreationMutex();}

SimpleMetadataAwareAspectInstanceFactory

SimpleMetadataAwareAspectInstanceFactorySimpleAspectInstanceFactory 的扩展实现,提供了 MetadataAwareAspectInstanceFactory 接口的功能,能够为每次调用 getAspectInstance() 时创建指定的 Aspect 类的实例,并返回与之关联的 AspectMetadata

public class SimpleMetadataAwareAspectInstanceFactory extends SimpleAspectInstanceFactory implements MetadataAwareAspectInstanceFactory {private final AspectMetadata metadata;public SimpleMetadataAwareAspectInstanceFactory(Class<?> aspectClass, String aspectName) {super(aspectClass);this.metadata = new AspectMetadata(aspectClass, aspectName);}@Overridepublic final AspectMetadata getAspectMetadata() {return this.metadata;}@Overridepublic Object getAspectCreationMutex() {return this;}@Overrideprotected int getOrderForAspectClass(Class<?> aspectClass) {return OrderUtils.getOrder(aspectClass, Ordered.LOWEST_PRECEDENCE);}}

SingletonMetadataAwareAspectInstanceFactory

SingletonMetadataAwareAspectInstanceFactorySingletonAspectInstanceFactory 的扩展,实现了 MetadataAwareAspectInstanceFactory 接口。它主要用于为给定的单例 aspect 实例提供元数据支持,并返回相同的 aspect 实例

@SuppressWarnings("serial")
public class SingletonMetadataAwareAspectInstanceFactory extends SingletonAspectInstanceFactory implements MetadataAwareAspectInstanceFactory, Serializable {private final AspectMetadata metadata;public SingletonMetadataAwareAspectInstanceFactory(Object aspectInstance, String aspectName) {super(aspectInstance);this.metadata = new AspectMetadata(aspectInstance.getClass(), aspectName);}@Overridepublic final AspectMetadata getAspectMetadata() {return this.metadata;}@Overridepublic Object getAspectCreationMutex() {return this;}@Overrideprotected int getOrderForAspectClass(Class<?> aspectClass) {return OrderUtils.getOrder(aspectClass, Ordered.LOWEST_PRECEDENCE);}}

BeanFactoryAspectInstanceFactory

BeanFactoryAspectInstanceFactory 是一个实现了 MetadataAwareAspectInstanceFactory 接口的类,它通过 Spring 的 BeanFactory 来实例化和管理 Aspect,支持单例与原型模式,并能够处理 AspectJ 元数据和生命周期。

@SuppressWarnings("serial")
public class BeanFactoryAspectInstanceFactory implements MetadataAwareAspectInstanceFactory, Serializable {private final BeanFactory beanFactory;private final String name;private final AspectMetadata aspectMetadata;public BeanFactoryAspectInstanceFactory(BeanFactory beanFactory, String name) {this(beanFactory, name, null);}public BeanFactoryAspectInstanceFactory(BeanFactory beanFactory, String name, @Nullable Class<?> type) {Assert.notNull(beanFactory, "BeanFactory must not be null");Assert.notNull(name, "Bean name must not be null");this.beanFactory = beanFactory;this.name = name;Class<?> resolvedType = type;if (resolvedType == null) {resolvedType = beanFactory.getType(name);Assert.notNull(resolvedType, "Unresolvable bean type - explicitly specify the aspect class");}this.aspectMetadata = new AspectMetadata(resolvedType, name);}@Overridepublic Object getAspectInstance() {return this.beanFactory.getBean(this.name);}@Override@Nullablepublic ClassLoader getAspectClassLoader() {return (this.beanFactory instanceof ConfigurableBeanFactory cbf ?cbf.getBeanClassLoader() : ClassUtils.getDefaultClassLoader());}@Overridepublic AspectMetadata getAspectMetadata() {return this.aspectMetadata;}@Override@Nullablepublic Object getAspectCreationMutex() {if (this.beanFactory.isSingleton(this.name)) {return null;}else {return this;}}@Overridepublic int getOrder() {Class<?> type = this.beanFactory.getType(this.name);if (type != null) {if (Ordered.class.isAssignableFrom(type) && this.beanFactory.isSingleton(this.name)) {return ((Ordered) this.beanFactory.getBean(this.name)).getOrder();}return OrderUtils.getOrder(type, Ordered.LOWEST_PRECEDENCE);}return Ordered.LOWEST_PRECEDENCE;}@Overridepublic String toString() {return getClass().getSimpleName() + ": bean name '" + this.name + "'";}}

PrototypeAspectInstanceFactory

PrototypeAspectInstanceFactory 继承自 BeanFactoryAspectInstanceFactory,用于通过 BeanFactory 创建原型模式的 Aspect 实例。它确保所提供的 Bean 是原型类型,如果不是,则抛出 IllegalArgumentException 异常。

@SuppressWarnings("serial")
public class PrototypeAspectInstanceFactory extends BeanFactoryAspectInstanceFactory implements Serializable {public PrototypeAspectInstanceFactory(BeanFactory beanFactory, String name) {super(beanFactory, name);if (!beanFactory.isPrototype(name)) {throw new IllegalArgumentException("Cannot use PrototypeAspectInstanceFactory with bean named '" + name + "': not a prototype");}}}

LazySingletonAspectInstanceFactoryDecorator

LazySingletonAspectInstanceFactoryDecorator 是一个装饰器,用于确保 MetadataAwareAspectInstanceFactory 只实例化一次。在首次访问时,它延迟实例化并缓存生成的 aspectInstance,后续访问直接返回缓存的实例。

@SuppressWarnings("serial")
public class LazySingletonAspectInstanceFactoryDecorator implements MetadataAwareAspectInstanceFactory, Serializable {private final MetadataAwareAspectInstanceFactory maaif;@Nullableprivate volatile Object materialized;public LazySingletonAspectInstanceFactoryDecorator(MetadataAwareAspectInstanceFactory maaif) {Assert.notNull(maaif, "AspectInstanceFactory must not be null");this.maaif = maaif;}@Overridepublic Object getAspectInstance() {Object aspectInstance = this.materialized;if (aspectInstance == null) {Object mutex = this.maaif.getAspectCreationMutex();if (mutex == null) {aspectInstance = this.maaif.getAspectInstance();this.materialized = aspectInstance;}else {synchronized (mutex) {aspectInstance = this.materialized;if (aspectInstance == null) {aspectInstance = this.maaif.getAspectInstance();this.materialized = aspectInstance;}}}}return aspectInstance;}public boolean isMaterialized() {return (this.materialized != null);}@Override@Nullablepublic ClassLoader getAspectClassLoader() {return this.maaif.getAspectClassLoader();}@Overridepublic AspectMetadata getAspectMetadata() {return this.maaif.getAspectMetadata();}@Override@Nullablepublic Object getAspectCreationMutex() {return this.maaif.getAspectCreationMutex();}@Overridepublic int getOrder() {return this.maaif.getOrder();}@Overridepublic String toString() {return "LazySingletonAspectInstanceFactoryDecorator: decorating " + this.maaif;}}
http://www.lryc.cn/news/593590.html

相关文章:

  • 零基础学习性能测试第二章-监控体系
  • OllyDbg技巧学习
  • Redis 如何保证高并发与高可用
  • Python爬虫实战:研究pefile库相关技术
  • PCB 混合介质叠层:材料特性匹配与性能提升的技术解析
  • 1. Spring AI概述
  • OSPF高级特性之Overflow
  • 【c++】提升用户体验:问答系统的交互优化实践——关于我用AI编写了一个聊天机器人……(12)
  • Buildroot vs Yocto:SDK 构建机制的核心差异与实践案例
  • 多线程 示例
  • QT窗口(8)-QFileDiag
  • esp32 sd卡
  • Kubernetes常用命令总结
  • MySQL 深度性能优化配置实战指南
  • 单例模式的设计与实现
  • Salesforce 与外部系统实时集成:基于事件驱动的异步集成架构
  • ChatGPT Agent深度解析:告别单纯问答,一个指令搞定复杂任务?
  • (LeetCode 面试经典 150 题) 49. 字母异位词分组 (哈希表)
  • 软件工程:可行性分析的任务及报告
  • picoCTF 2024: [[NoSQL]] Injection - Writeup
  • JAVA中的Collections 类
  • 【数据结构】二叉树初阶详解(一):树与二叉树基础 + 堆结构全解析
  • windows wsl2-05-docker 安装笔记
  • 光盘存储器的组成与分类
  • 从“数字土著”到“数据公民”:K-12数据伦理课程的设计、实施与成效追踪研究
  • Codeforces Round 1037 (Div. 3)(补题)
  • Codeforces Round 1037(Div.3)
  • 搭建比分网服务器怎么选数据不会卡顿?
  • 配置华为交换机接口链路聚合-支持服务器多网卡Bind
  • 数据结构:字符串(Strings)