[spring6: AspectMetadata & AspectInstanceFactory]-源码解析

发布于:2025-07-20 ⋅ 阅读:(17) ⋅ 点赞:(0)

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 pattern
				this.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();

	@Nullable
	ClassLoader 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;
	}

	@Override
	public 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
	@Nullable
	public ClassLoader getAspectClassLoader() {
		return this.aspectClass.getClassLoader();
	}
	
	@Override
	public 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;
	}

	@Override
	public final Object getAspectInstance() {
		return this.aspectInstance;
	}

	@Override
	@Nullable
	public ClassLoader getAspectClassLoader() {
		return this.aspectInstance.getClass().getClassLoader();
	}

	@Override
	public 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();

	@Nullable
	Object 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);
	}

	@Override
	public final AspectMetadata getAspectMetadata() {
		return this.metadata;
	}

	@Override
	public Object getAspectCreationMutex() {
		return this;
	}

	@Override
	protected 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);
	}

	@Override
	public final AspectMetadata getAspectMetadata() {
		return this.metadata;
	}

	@Override
	public Object getAspectCreationMutex() {
		return this;
	}

	@Override
	protected 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);
	}

	@Override
	public Object getAspectInstance() {
		return this.beanFactory.getBean(this.name);
	}

	@Override
	@Nullable
	public ClassLoader getAspectClassLoader() {
		return (this.beanFactory instanceof ConfigurableBeanFactory cbf ?
				cbf.getBeanClassLoader() : ClassUtils.getDefaultClassLoader());
	}

	@Override
	public AspectMetadata getAspectMetadata() {
		return this.aspectMetadata;
	}

	@Override
	@Nullable
	public Object getAspectCreationMutex() {
		if (this.beanFactory.isSingleton(this.name)) {
			return null;
		}
		else {
			return this;
		}
	}
	
	@Override
	public 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;
	}

	@Override
	public 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;

	@Nullable
	private volatile Object materialized;

	public LazySingletonAspectInstanceFactoryDecorator(MetadataAwareAspectInstanceFactory maaif) {
		Assert.notNull(maaif, "AspectInstanceFactory must not be null");
		this.maaif = maaif;
	}

	@Override
	public 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
	@Nullable
	public ClassLoader getAspectClassLoader() {
		return this.maaif.getAspectClassLoader();
	}

	@Override
	public AspectMetadata getAspectMetadata() {
		return this.maaif.getAspectMetadata();
	}

	@Override
	@Nullable
	public Object getAspectCreationMutex() {
		return this.maaif.getAspectCreationMutex();
	}

	@Override
	public int getOrder() {
		return this.maaif.getOrder();
	}

	@Override
	public String toString() {
		return "LazySingletonAspectInstanceFactoryDecorator: decorating " + this.maaif;
	}

}

网站公告

今日签到

点亮在社区的每一天
去签到