主頁 > 後端開發 > 死磕Spring之AOP篇 - Spring AOP注解驅動與XML配置

死磕Spring之AOP篇 - Spring AOP注解驅動與XML配置

2021-04-24 06:20:39 後端開發

該系列文章是本人在學習 Spring 的程序中總結下來的,里面涉及到相關原始碼,可能對讀者不太友好,請結合我的原始碼注釋 Spring 原始碼分析 GitHub 地址 進行閱讀,

Spring 版本:5.1.14.RELEASE

在開始閱讀 Spring AOP 原始碼之前,需要對 Spring IoC 有一定的了解,可查看我的 《死磕Spring之IoC篇 - 文章導讀》 這一系列文章

了解 AOP 相關術語,可先查看 《Spring AOP 常見面試題) 》 這篇文章

該系列其他文章請查看:《死磕 Spring 之 AOP 篇 - 文章導讀》

通過前面關于 Spring AOP 的所有文章,我們對 Spring AOP 的整個 AOP 實作邏輯進行了比較詳細的分析,例如 Spring AOP 的自動代理,JDK 動態代理或 CGLIB 動態代理兩種方式創建的代理物件的攔截處理程序等內容都有講到,本文將會分析 Spring AOP 的注解驅動,如何引入 AOP 模塊,包括如何處理 Spring AOP 的 XML 配置,

在 Spring AOP 中可以通過 @EnableAspectJAutoProxy 注解驅動整個 AOP 模塊,我們先一起來看看這個注解,

@EnableAspectJAutoProxy 注解

org.springframework.context.annotation.EnableAspectJAutoProxy,開啟 Spring AOP 整個模塊的注解

/**
 * @since 3.1
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(AspectJAutoProxyRegistrar.class)
public @interface EnableAspectJAutoProxy {

	/**
	 * 是否開啟類代理,也就是是否開啟 CGLIB 動態代理
	 */
	boolean proxyTargetClass() default false;

	/**
	 * 是否需要暴露代理物件
	 * @since 4.3.1
	 */
	boolean exposeProxy() default false;
}

該注解上面有一個 @Import 注解,它的 valueAspectJAutoProxyRegistrar.class 類,

這里先講一下 @Import 注解的原理,在 Spring IoC 初始化完 BeanFactory 后會有一個 BeanDefinitionRegistryPostProcessor 對其進行后置處理,對配置類(例如 @Configuration 注解標注的 Bean)進行處理,如果這個 BeanDefinition 包含 @Import 注解,則獲取注解的值,進行下面的處理:

  • 如果是一個 ImportSelector 物件,則呼叫其 String[] selectImports(AnnotationMetadata) 方法獲取需要匯入的 Bean 的名稱
  • 否則,如果是一個 ImportBeanDefinitionRegistrar 物件,先保存起來,在后面呼叫其 registerBeanDefinitions(AnnotationMetadata, BeanDefinitionRegistry) 方法,支持注冊相關 Bean
  • 否則,會注冊這個 Bean

關于 @Import 注解不熟悉的小伙伴查看我的另一篇 《死磕Spring之IoC篇 - @Bean 等注解的實作原理》 文章

所以說 @EnableAspectJAutoProxy 注解需要標注在能夠被 Spring 掃描的類上面,例如 @Configuration 標注的類,其中 AspectJAutoProxyRegistrar 就是 ImportBeanDefinitionRegistrar 的實作類,我們一起來看看,

AspectJAutoProxyRegistrar

org.springframework.context.annotation.AspectJAutoProxyRegistrar,在 @EnableAspectJAutoProxy 注解中被匯入

class AspectJAutoProxyRegistrar implements ImportBeanDefinitionRegistrar {

	@Override
	public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

		// <1> 注冊一個 AnnotationAwareAspectJAutoProxyCreator 自動代理物件(如果沒有注冊的話),設定為優先級最高
		AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry);

		// <2> 獲取 @EnableAspectJAutoProxy 注解的配置資訊
		AnnotationAttributes enableAspectJAutoProxy = AnnotationConfigUtils.attributesFor(importingClassMetadata, EnableAspectJAutoProxy.class);
		// <3> 如果注解配置資訊不為空,則根據配置設定 AnnotationAwareAspectJAutoProxyCreator 的屬性
		if (enableAspectJAutoProxy != null) {
			if (enableAspectJAutoProxy.getBoolean("proxyTargetClass")) {
				// 設定 `proxyTargetClass` 為 `true`(開啟類代理,也就是開啟 CGLIB 動態代理)
				AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
			}
			if (enableAspectJAutoProxy.getBoolean("exposeProxy")) {
				// 設定 `exposeProxy` 為 `true`(需要暴露代理物件,也就是在 Advice 或者被攔截的方法中可以通過 AopContext 獲取代理物件)
				AopConfigUtils.forceAutoProxyCreatorToExposeProxy(registry);
			}
		}
	}
}

可以看到它注冊 BeanDefinition 的程序如下:

  1. 通過 AopConfigUtils 注冊一個 AnnotationAwareAspectJAutoProxyCreator 自動代理物件(如果沒有注冊的話),設定為優先級最高
  2. 獲取 @EnableAspectJAutoProxy 注解的配置資訊
  3. 如果注解配置資訊不為空,則根據配置設定 AnnotationAwareAspectJAutoProxyCreator 的屬性
    • 如果 proxyTargetClasstrue,則進行設定(開啟類代理,也就是開啟 CGLIB 動態代理)
    • 如果 exposeProxytrue,則進行設定(需要暴露代理物件,也就是在 Advice 或者被攔截的方法中可以通過 AopContext 獲取代理物件)

可以看到會注冊一個 AnnotationAwareAspectJAutoProxyCreator 自動代理物件,是不是很熟悉,就是在前面文章講到的自動代理物件,那么就開啟了 Spring AOP 自動代理,也就是開啟了 Spring AOP 整個模塊,

AopConfigUtils

org.springframework.aop.config.AopConfigUtils,AOP 工具類

建構式

public abstract class AopConfigUtils {

	/**
	 * The bean name of the internally managed auto-proxy creator.
	 */
	public static final String AUTO_PROXY_CREATOR_BEAN_NAME =
			"org.springframework.aop.config.internalAutoProxyCreator";

	/**
	 * Stores the auto proxy creator classes in escalation order.
	 */
	private static final List<Class<?>> APC_PRIORITY_LIST = new ArrayList<>(3);

	static {
		// Set up the escalation list...
		APC_PRIORITY_LIST.add(InfrastructureAdvisorAutoProxyCreator.class);
		APC_PRIORITY_LIST.add(AspectJAwareAdvisorAutoProxyCreator.class);
		APC_PRIORITY_LIST.add(AnnotationAwareAspectJAutoProxyCreator.class);
	}
}

上面定義了 AspectJAwareAdvisorAutoProxyCreator 幾種子類的優先級,排在后面優先級越高

registerAspectJAnnotationAutoProxyCreatorIfNecessary 方法

@Nullable
public static BeanDefinition registerAspectJAnnotationAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry) {
    return registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry, null);
}

@Nullable
public static BeanDefinition registerAspectJAnnotationAutoProxyCreatorIfNecessary(
        BeanDefinitionRegistry registry, @Nullable Object source) {

    // 注冊 AnnotationAwareAspectJAutoProxyCreator Bean
    return registerOrEscalateApcAsRequired(AnnotationAwareAspectJAutoProxyCreator.class, registry, source);
}

@Nullable
private static BeanDefinition registerOrEscalateApcAsRequired(
        Class<?> cls, BeanDefinitionRegistry registry, @Nullable Object source) {

    Assert.notNull(registry, "BeanDefinitionRegistry must not be null");

    // <1> 如果 `org.springframework.aop.config.internalAutoProxyCreator` 已注冊
    if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) {
        // <1.1> 獲取對應的 BeanDefinition 物件
        BeanDefinition apcDefinition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME);
        // <1.2> 如果已注冊的 `internalAutoProxyCreator` 和入參的 Class 不相等,說明可能是繼承關系
        if (!cls.getName().equals(apcDefinition.getBeanClassName())) {
            // <1.2.1> 獲取已注冊的 `internalAutoProxyCreator` 的優先級
            int currentPriority = findPriorityForClass(apcDefinition.getBeanClassName());
            // <1.2.2> 獲取需要注冊的 `internalAutoProxyCreator` 的優先級
            int requiredPriority = findPriorityForClass(cls);
            // InfrastructureAdvisorAutoProxyCreator < AspectJAwareAdvisorAutoProxyCreator < AnnotationAwareAspectJAutoProxyCreator
            // 三者都是 AbstractAutoProxyCreator 自動代理物件的子類
            if (currentPriority < requiredPriority) {
                // <1.2.3> 如果需要注冊的優先級更高,那取代已注冊的 Class 物件
                apcDefinition.setBeanClassName(cls.getName());
            }
        }
        // <1.3> 因為已注冊,則回傳 `null`
        return null;
    }

    // <2> 沒有注冊,則創建一個 RootBeanDefinition 物件進行注冊
    RootBeanDefinition beanDefinition = new RootBeanDefinition(cls);
    // <3> 設定來源
    beanDefinition.setSource(source);
    // <4> 設定為最高優先級
    beanDefinition.getPropertyValues().add("order", Ordered.HIGHEST_PRECEDENCE);
    // <5> 設定角色為**ROLE_INFRASTRUCTURE**,表示是 Spring 框架內部的 Bean
    beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
    // <6> 注冊自動代理的 Bean,名稱為 `org.springframework.aop.config.internalAutoProxyCreator`
    registry.registerBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME, beanDefinition);
    // <7> 回傳剛注冊的 RootBeanDefinition 物件
    return beanDefinition;
}

可以看到會注冊一個 AnnotationAwareAspectJAutoProxyCreator 自動代理 Bean,程序如下:

  1. 如果 org.springframework.aop.config.internalAutoProxyCreator 已注冊
    1. 獲取對應的 BeanDefinition 物件
    2. 如果已注冊的 internalAutoProxyCreator 和入參的 Class 不相等,說明可能是繼承關系
      1. 獲取已注冊的 internalAutoProxyCreator 的優先級
      2. 獲取需要注冊的 internalAutoProxyCreator 的優先級
      3. 如果需要注冊的優先級更高,那取代已注冊的 Class 物件,InfrastructureAdvisorAutoProxyCreator < AspectJAwareAdvisorAutoProxyCreator < AnnotationAwareAspectJAutoProxyCreator
    3. 否則,因為已注冊,則回傳 null
  2. 否則,沒有注冊,則創建一個 RootBeanDefinition 物件進行注冊
  3. 設定來源
  4. 設定為最高優先級
  5. 設定角色為ROLE_INFRASTRUCTURE,表示是 Spring 框架內部的 Bean
  6. 注冊自動代理的 Bean,名稱為 org.springframework.aop.config.internalAutoProxyCreator
  7. 回傳剛注冊的 RootBeanDefinition 物件

整個程序很簡單,如果已注冊自動代理物件,則判斷當前需要注冊的是否優先級更高,如果更高則修改其對應的 Class 名稱;如果沒有注冊,那么注冊這個代理物件,設定優先級最高,

------------------------------------

AOP XML 配置決議程序

再開始之前對于 Spring XML 組態檔不熟悉的小伙伴可以看看我的 《死磕Spring之IoC篇 - 決議自定義標簽(XML 檔案)》 這篇文章,在 Spring 中對于非默認命名空間的標簽需要通過指定的 NamespaceHandler 來處理,在 Spring 的 XML 組態檔中都是在 <beans /> 標簽內定義資料,需要指定 http://www.springframework.org/schema/beans 作為命名空間,那么對于 http://www.springframework.org/schema/aop 就需要指定 NamespaceHandler 來處理,我們來看到 spring-aop 模塊下的 META-INF/spring.handlers 組態檔:

http\://www.springframework.org/schema/aop=org.springframework.aop.config.AopNamespaceHandler

Spring AOP 相關的標簽需要 AopNamespaceHandler 進行處理

AopNamespaceHandler

org.springframework.aop.config.AopNamespaceHandler,繼承 NamespaceHandlerSupport 抽象類,Spring AOP 命名空間下的標簽處理器

public class AopNamespaceHandler extends NamespaceHandlerSupport {

	/**
	 * Register the {@link BeanDefinitionParser BeanDefinitionParsers} for the
	 * '{@code config}', '{@code spring-configured}', '{@code aspectj-autoproxy}'
	 * and '{@code scoped-proxy}' tags.
	 */
	@Override
	public void init() {
		// In 2.0 XSD as well as in 2.1 XSD.
		// <aop:config /> 標簽的決議器
		registerBeanDefinitionParser("config", new ConfigBeanDefinitionParser());
		// <aop:aspectj-autoproxy /> 標簽的決議器
		registerBeanDefinitionParser("aspectj-autoproxy", new AspectJAutoProxyBeanDefinitionParser());
		// <aop:scoped-proxy /> 標簽的決議器
		registerBeanDefinitionDecorator("scoped-proxy", new ScopedProxyBeanDefinitionDecorator());

		// Only in 2.0 XSD: moved to context namespace as of 2.1
		registerBeanDefinitionParser("spring-configured", new SpringConfiguredBeanDefinitionParser());
	}
}

public abstract class NamespaceHandlerSupport implements NamespaceHandler {

	private final Map<String, BeanDefinitionParser> parsers = new HashMap<>();
    
    private final Map<String, BeanDefinitionDecorator> decorators = new HashMap<>();
    
    protected final void registerBeanDefinitionParser(String elementName, BeanDefinitionParser parser) {
        this.parsers.put(elementName, parser);
    }
    
    protected final void registerBeanDefinitionDecorator(String elementName, BeanDefinitionDecorator dec) {
		this.decorators.put(elementName, dec);
	}
}

在這個 NamespaceHandler 的 init() 初始化方法中,會往 parsers 中注冊幾個標簽決議器或者裝飾器:

  • <aop:config />:ConfigBeanDefinitionParser
  • <aop:aspectj-autoproxy />:AspectJAutoProxyBeanDefinitionParser
  • <aop:scoped-proxy />:ScopedProxyBeanDefinitionDecorator

繼續看到 NamespaceHandlerSupport 這個方法:

@Override
@Nullable
public BeanDefinition parse(Element element, ParserContext parserContext) {
    // <1> 獲得元素對應的 BeanDefinitionParser 物件
    BeanDefinitionParser parser = findParserForElement(element, parserContext);
    // <2> 執行決議
    return (parser != null ? parser.parse(element, parserContext) : null);
}
@Nullable
private BeanDefinitionParser findParserForElement(Element element, ParserContext parserContext) {
    // 獲得元素名
    String localName = parserContext.getDelegate().getLocalName(element);
    // 獲得 BeanDefinitionParser 物件
    BeanDefinitionParser parser = this.parsers.get(localName);
    if (parser == null) {
        parserContext.getReaderContext().fatal(
                "Cannot locate BeanDefinitionParser for element [" + localName + "]", element);
    }
    return parser;
}

@Override
@Nullable
public BeanDefinitionHolder decorate(
        Node node, BeanDefinitionHolder definition, ParserContext parserContext) {
    // 根據標簽名獲取 BeanDefinitionDecorator 物件
    BeanDefinitionDecorator decorator = findDecoratorForNode(node, parserContext);
    return (decorator != null ? decorator.decorate(node, definition, parserContext) : null);
}
@Nullable
private BeanDefinitionDecorator findDecoratorForNode(Node node, ParserContext parserContext) {
    BeanDefinitionDecorator decorator = null;
    // 獲得元素名
    String localName = parserContext.getDelegate().getLocalName(node);
    if (node instanceof Element) {
        decorator = this.decorators.get(localName);
    }
    else if (node instanceof Attr) {
        decorator = this.attributeDecorators.get(localName);
    }
    else {
        parserContext.getReaderContext().fatal(
                "Cannot decorate based on Nodes of type [" + node.getClass().getName() + "]", node);
    }
    if (decorator == null) {
        parserContext.getReaderContext().fatal("Cannot locate BeanDefinitionDecorator for " +
                (node instanceof Element ? "element" : "attribute") + " [" + localName + "]", node);
    }
    return decorator;
}

會根據標簽名稱找到對應的 BeanDefinitionParser 決議器進行決議,那么現在思路清晰了,上面不同的標簽對應著不同的 BeanDefinitionParser 或者 BeanDefinitionDecorator,我們來看看是怎么處理的,

<aop:aspectj-autoproxy />

<beans>
    <aop:aspectj-autoproxy proxy-target- expose-proxy="false" />
</beans>

這個標簽的作用和 @EnableAspectJAutoProxy 注解相同,開啟整個 Spring AOP 模塊,原理也相同,注冊一個 AnnotationAwareAspectJAutoProxyCreator 自動代理物件

AspectJAutoProxyBeanDefinitionParser

org.springframework.aop.config.AspectJAutoProxyBeanDefinitionParser<aop:aspectj-autoproxy /> 標簽對應 BeanDefinitionParse 決議器

class AspectJAutoProxyBeanDefinitionParser implements BeanDefinitionParser {

	@Override
	@Nullable
	public BeanDefinition parse(Element element, ParserContext parserContext) {
		// 決議 <aop:aspectj-autoproxy /> 標簽
		// 注冊 AnnotationAwareAspectJAutoProxyCreator 自動代理物件(如果沒有注冊的話),設定為優先級最高
		// 程序和 @EnableAspectJAutoProxy
		AopNamespaceUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(parserContext, element);
		// 決議 <aop:include /> 子標簽,用于指定需要開啟代理的路徑
		extendBeanDefinition(element, parserContext);
		return null;
	}

	private void extendBeanDefinition(Element element, ParserContext parserContext) {
		BeanDefinition beanDef = parserContext.getRegistry().getBeanDefinition(AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME);
		if (element.hasChildNodes()) {
			addIncludePatterns(element, parserContext, beanDef);
		}
	}

	private void addIncludePatterns(Element element, ParserContext parserContext, BeanDefinition beanDef) {
		ManagedList<TypedStringValue> includePatterns = new ManagedList<>();
		NodeList childNodes = element.getChildNodes();
		for (int i = 0; i < childNodes.getLength(); i++) {
			Node node = childNodes.item(i);
			if (node instanceof Element) {
				Element includeElement = (Element) node;
				TypedStringValue valueHolder = new TypedStringValue(includeElement.getAttribute("name"));
				valueHolder.setSource(parserContext.extractSource(includeElement));
				includePatterns.add(valueHolder);
			}
		}
		if (!includePatterns.isEmpty()) {
			includePatterns.setSource(parserContext.extractSource(element));
			beanDef.getPropertyValues().add("includePatterns", includePatterns);
		}
	}
}

<aop:aspectj-autoproxy /> 標簽的決議程序先通過 AopNamespaceUtils 工具類注冊一個 AnnotationAwareAspectJAutoProxyCreator 自動代理物件,然后繼續決議 <aop:include /> 子標簽,用于指定需要開啟代理的路徑

AopNamespaceUtils

org.springframework.aop.config.AopNamespaceUtils,Spring AOP XML 組態檔決議工具類

public abstract class AopNamespaceUtils {

	public static final String PROXY_TARGET_CLASS_ATTRIBUTE = "proxy-target-class";
	private static final String EXPOSE_PROXY_ATTRIBUTE = "expose-proxy";

	public static void registerAspectJAnnotationAutoProxyCreatorIfNecessary(
			ParserContext parserContext, Element sourceElement) {

		// <1> 注冊 AnnotationAwareAspectJAutoProxyCreator 自動代理物件(如果沒有注冊的話),設定為優先級最高
		BeanDefinition beanDefinition = AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(
				parserContext.getRegistry(), parserContext.extractSource(sourceElement));
		// <2> 則根據 <aop:aspectj-autoproxy /> 標簽的配置設定 AnnotationAwareAspectJAutoProxyCreator 的屬性
		useClassProxyingIfNecessary(parserContext.getRegistry(), sourceElement);
		// <3> 將注冊的 BeanDefinition 也放入 `parserContext` 背景關系中
		registerComponentIfNecessary(beanDefinition, parserContext);
	}

	private static void useClassProxyingIfNecessary(BeanDefinitionRegistry registry, @Nullable Element sourceElement) {
		// 如果 <aop:aspectj-autoproxy /> 標簽不為空
		if (sourceElement != null) {
			boolean proxyTargetClass = Boolean.parseBoolean(sourceElement.getAttribute(PROXY_TARGET_CLASS_ATTRIBUTE));
			if (proxyTargetClass) {
				// 設定 `proxyTargetClass` 為 `true`(開啟類代理,也就是開啟 CGLIB 動態代理)
				AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
			}
			boolean exposeProxy = Boolean.parseBoolean(sourceElement.getAttribute(EXPOSE_PROXY_ATTRIBUTE));
			if (exposeProxy) {
				// 設定 `exposeProxy` 為 `true`(需要暴露代理物件,也就是在 Advice 或者被攔截的方法中可以通過 AopContext 獲取代理物件)
				AopConfigUtils.forceAutoProxyCreatorToExposeProxy(registry);
			}
		}
	}

	private static void registerComponentIfNecessary(@Nullable BeanDefinition beanDefinition, ParserContext parserContext) {
		if (beanDefinition != null) {
			parserContext.registerComponent(
					new BeanComponentDefinition(beanDefinition, AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME));
		}
	}
}

注冊 AnnotationAwareAspectJAutoProxyCreator 自動代理物件的程序和 @EnableAspectJAutoProxy 注解型別,這里不再做講述

<aop:scoped-proxy />

<beans>
    <bean id="echoService"  >
    	<aop:scoped-proxy />
	</bean>
</beans>

<aop:scoped-proxy /> 標簽需要定義在 <bean /> 中,用來裝飾這個 Bean,會生成一個 ScopedProxyFactoryBean 型別的 RootBeanDefinition 物件并注冊,ScopedProxyFactoryBean 是一個 FactoryBean,在其 getObject() 方法中回傳的是一個代理物件,也就是說 <aop:scoped-proxy /> 標簽可以將一個 Bean 進行 AOP 代理,

ScopedProxyBeanDefinitionDecorator

org.springframework.aop.config.ScopedProxyBeanDefinitionDecorator<aop:scoped-proxy /> 標簽對應的 BeanDefinitionDecorator 裝飾器

class ScopedProxyBeanDefinitionDecorator implements BeanDefinitionDecorator {

	private static final String PROXY_TARGET_CLASS = "proxy-target-class";

	@Override
	public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definition, ParserContext parserContext) {
		boolean proxyTargetClass = true;
		if (node instanceof Element) {
			Element ele = (Element) node;
			if (ele.hasAttribute(PROXY_TARGET_CLASS)) {
				proxyTargetClass = Boolean.valueOf(ele.getAttribute(PROXY_TARGET_CLASS));
			}
		}

		// Register the original bean definition as it will be referenced by the scoped proxy
		// and is relevant for tooling (validation, navigation).
		// 創建一個 ScopedProxyFactoryBean 型別的 RootBeanDefinition 物件并注冊
		// ScopedProxyFactoryBean 用于裝飾 `definition`,進行 AOP 代理
		BeanDefinitionHolder holder = ScopedProxyUtils.createScopedProxy(definition, parserContext.getRegistry(), proxyTargetClass);
		String targetBeanName = ScopedProxyUtils.getTargetBeanName(definition.getBeanName());
		parserContext.getReaderContext().fireComponentRegistered(
				new BeanComponentDefinition(definition.getBeanDefinition(), targetBeanName));
		return holder;
	}
}

<aop:config />

<beans>
    <aop:aspectj-autoproxy/>
    <bean id="aspectXmlConfig" />
    <aop:config>
        <aop:pointcut id="anyPublicStringMethod" expression="execution(public String *(..))"/>
        <aop:advisor advice-ref="echoServiceMethodInterceptor" pointcut-ref="anyPublicStringMethod" />
        <aop:aspect id="AspectXmlConfig" ref="aspectXmlConfig">
            <aop:pointcut id="anyPublicMethod" expression="execution(public * *(..))"/>
            <aop:around method="aroundAnyPublicMethod" pointcut-ref="anyPublicMethod"/>
            <aop:before method="beforeAnyPublicMethod" pointcut-ref="anyPublicMethod"/>
            <aop:before method="beforeAnyPublicMethod" pointcut="execution(public * *(..))"/>
            <aop:after method="finalizeAnyPublicMethod" pointcut-ref="anyPublicMethod"/>
            <aop:after-returning method="afterAnyPublicMethod" pointcut-ref="anyPublicMethod"/>
            <aop:after-throwing method="afterThrowingAnyPublicMethod" pointcut-ref="anyPublicMethod"/>
        </aop:aspect>
    </aop:config>
</beans>

<aop:config> 標簽內可以定義 AspectJ 切面的相關資訊,例如 Pointcut、Advisor 和 Advice;同時也會注冊一個 Spring AOP 自動代理物件(如果有必要的話),不過 是注冊 AspectJAwareAdvisorAutoProxyCreator,只能決議處理 Spring IoC 中 Advisor 型別的 Bean,無法決議 @AspectJ 等相關注解,所以我們最好使用 <aop:aspectj-autoproxy/> 標簽來驅動 Spring AOP 模塊,

ConfigBeanDefinitionParser

org.springframework.aop.config.ConfigBeanDefinitionParser<aop:config /> 標簽對應的 BeanDefinitionParser 決議器,我們來看到它的 parse(..) 方法

@Override
@Nullable
public BeanDefinition parse(Element element, ParserContext parserContext) {
    CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), parserContext.extractSource(element));
    parserContext.pushContainingComponent(compositeDef);

    // <1> 決議 <aop:config /> 標簽
    // 注冊 AspectJAwareAdvisorAutoProxyCreator 自動代理物件(如果需要的話),設定為優先級最高
    // 程序和 @EnableAspectJAutoProxy、<aop:aspectj-autoproxy /> 差不多
    configureAutoProxyCreator(parserContext, element);

    // <2> 獲取 <aop:config /> 的子標簽,遍歷進行處理
    List<Element> childElts = DomUtils.getChildElements(element);
    for (Element elt: childElts) {
        // 獲取子標簽的名稱
        String localName = parserContext.getDelegate().getLocalName(elt);
        if (POINTCUT.equals(localName)) {
            // <2.1> 處理 <aop:pointcut /> 子標簽,決議出 AspectJExpressionPointcut 物件并注冊
            parsePointcut(elt, parserContext);
        }
        else if (ADVISOR.equals(localName)) {
            // <2.2> 處理 <aop:advisor /> 子標簽,決議出 DefaultBeanFactoryPointcutAdvisor 物件并注冊,了指定 Advice 和 Pointcut(如果有)
            parseAdvisor(elt, parserContext);
        }
        else if (ASPECT.equals(localName)) {
            // <2.3> 處理 <aop:aspectj /> 子標簽,決議出所有的 AspectJPointcutAdvisor 物件并注冊,里面包含了 Advice 物件和對應的 Pointcut 物件
            // 同時存在 Pointcut 配置,也會決議出 AspectJExpressionPointcut 物件并注冊
            parseAspect(elt, parserContext);
        }
    }

    // <3> 將 `parserContext` 背景關系中已注冊的 BeanDefinition 合并到上面 `compositeDef` 中(暫時忽略)
    parserContext.popAndRegisterContainingComponent();
    return null;
}

該方法的處理程序如下:

  1. 決議 <aop:config /> 標簽,注冊 AspectJAwareAdvisorAutoProxyCreator 自動代理物件(如果需要的話),設定為優先級最高

    private void configureAutoProxyCreator(ParserContext parserContext, Element element) {
        // 注冊 AspectJAwareAdvisorAutoProxyCreator 自動代理物件(如果需要的話)
        AopNamespaceUtils.registerAspectJAutoProxyCreatorIfNecessary(parserContext, element);
    }
    

    程序和 @EnableAspectJAutoProxy<aop:aspectj-autoproxy /> 的決議程序差不多,這里不再進行展述

  2. 獲取 <aop:config /> 的子標簽,遍歷進行處理

    1. 呼叫 parsePointcut(..) 方法,處理 <aop:pointcut /> 子標簽,決議出 AspectJExpressionPointcut 物件并注冊
    2. 呼叫 parseAdvisor(..) 方法,處理 <aop:advisor /> 子標簽,決議出 DefaultBeanFactoryPointcutAdvisor 物件并注冊,了指定 Advice 和 Pointcut(如果有)
    3. 呼叫 parseAspect(..) 方法,處理 <aop:aspectj /> 子標簽,決議出所有的 AspectJPointcutAdvisor 物件并注冊,里面包含了 Advice 物件和對應的 Pointcut 物件;同時存在 Pointcut 配置,也會決議出 AspectJExpressionPointcut 物件并注冊

我們依次來看看你上面三種子標簽的處理程序

<aop:pointcut />

<beans>
    <aop:aspectj-autoproxy/>
    <bean id="aspectXmlConfig" />
    <aop:config>
        <aop:pointcut id="anyPublicStringMethod" expression="execution(public String *(..))"/>
    </aop:config>
</beans>

處理程序在 parsePointcut(..) 方法中,如下:

// ConfigBeanDefinitionParser.java
private AbstractBeanDefinition parsePointcut(Element pointcutElement, ParserContext parserContext) {
    // <1> 獲取 <aop:pointcut /> 標簽的 `id` 和 `expression` 配置
    String id = pointcutElement.getAttribute(ID);
    String expression = pointcutElement.getAttribute(EXPRESSION);

    AbstractBeanDefinition pointcutDefinition = null;

    try {
        this.parseState.push(new PointcutEntry(id));
        // <2> 創建一個 AspectJExpressionPointcut 型別的 RootBeanDefinition 物件
        pointcutDefinition = createPointcutDefinition(expression);
        // <3> 設定來源
        pointcutDefinition.setSource(parserContext.extractSource(pointcutElement));

        String pointcutBeanName = id;
        // <4> 注冊這個 AspectJExpressionPointcut 物件
        if (StringUtils.hasText(pointcutBeanName)) {
            // <4.1> 如果 `id` 配置不為空,則取其作為名稱
            parserContext.getRegistry().registerBeanDefinition(pointcutBeanName, pointcutDefinition);
        }
        else {
            // <4.2> 否則,自動生成名稱,也就是取 `className`
            pointcutBeanName = parserContext.getReaderContext().registerWithGeneratedName(pointcutDefinition);
        }

        // <5> 將注冊的 BeanDefinition 包裝成 ComponentDefinition 放入 `parserContext` 背景關系中,暫時忽略
        parserContext.registerComponent(
                new PointcutComponentDefinition(pointcutBeanName, pointcutDefinition, expression));
    }
    finally {
        this.parseState.pop();
    }

    return pointcutDefinition;
}

決議程序大致如下:

  1. 獲取 <aop:pointcut /> 標簽的 idexpression 配置

  2. 根據 expression 運算式創建一個 AspectJExpressionPointcut 型別的 RootBeanDefinition 物件,如下:

    protected AbstractBeanDefinition createPointcutDefinition(String expression) {
        // <1> 創建一個 AspectJExpressionPointcut 型別的 RootBeanDefinition 物件
        RootBeanDefinition beanDefinition = new RootBeanDefinition(AspectJExpressionPointcut.class);
        // <2> 設定為原型模式,需要保證每次獲取到的 Pointcut 物件都是新的,防止在某些地方被修改而影響到其他地方
        beanDefinition.setScope(BeanDefinition.SCOPE_PROTOTYPE);
        // <3> 設定為是 Spring 內部合成的
        beanDefinition.setSynthetic(true);
        // <4> 添加 `expression` 屬性值
        beanDefinition.getPropertyValues().add(EXPRESSION, expression);
        // <5> 回傳剛創建的 RootBeanDefinition 物件
        return beanDefinition;
    }
    
  3. 設定來源

  4. 注冊這個 AspectJExpressionPointcut 物件

    1. 如果 id 配置不為空,則取其作為名稱
    2. 否則,自動生成名稱,也就是取 className
  5. 將注冊的 BeanDefinition 包裝成 ComponentDefinition 放入 parserContext 背景關系中,暫時忽略

<aop:advisor />

<beans>
    <aop:aspectj-autoproxy/>
    <bean id="aspectXmlConfig" />
    <aop:config>
        <aop:pointcut id="anyPublicStringMethod" expression="execution(public String *(..))"/>
        <aop:advisor advice-ref="echoServiceMethodInterceptor" pointcut-ref="anyPublicStringMethod" />
    </aop:config>
</beans>

處理程序在 parseAdvisor(..) 方法中,如下:

// ConfigBeanDefinitionParser.java
private void parseAdvisor(Element advisorElement, ParserContext parserContext) {
    // <1> 決議 <aop:advisor /> 標簽
    // 創建一個 DefaultBeanFactoryPointcutAdvisor 型別的 RootBeanDefinition 物件,并指定了 Advice
    AbstractBeanDefinition advisorDef = createAdvisorBeanDefinition(advisorElement, parserContext);
    // <2> 獲取 `id` 屬性
    String id = advisorElement.getAttribute(ID);

    try {
        this.parseState.push(new AdvisorEntry(id));
        String advisorBeanName = id;
        // <3> 注冊第 `1` 步創建的 RootBeanDefinition
        if (StringUtils.hasText(advisorBeanName)) {
            // <3.1> 如果 `id` 不為空,則取其作為名稱
            parserContext.getRegistry().registerBeanDefinition(advisorBeanName, advisorDef);
        }
        else {
            // <3.2> 否則,生成一個名稱,也就是 `className`
            advisorBeanName = parserContext.getReaderContext().registerWithGeneratedName(advisorDef);
        }

        // <4> 獲取這個 Advisor 對應的 Pointcut(也許就是一個 AspectJExpressionPointcut,也可能是參考的 Pointcut 的名稱)
        Object pointcut = parsePointcutProperty(advisorElement, parserContext);
        // <4.1> 如果是 AspectJExpressionPointcut
        if (pointcut instanceof BeanDefinition) {
            // 第 `1` 步創建的 RootBeanDefinition 添加 `pointcut` 屬性,指向這個 AspectJExpressionPointcut
            advisorDef.getPropertyValues().add(POINTCUT, pointcut);
            parserContext.registerComponent(
                    new AdvisorComponentDefinition(advisorBeanName, advisorDef, (BeanDefinition) pointcut));
        }
        // <4.2> 否則,如果是一個參考的 Pointcut 的名稱
        else if (pointcut instanceof String) {
            // 第 `1` 步創建的 RootBeanDefinition 添加 `pointcut` 屬性,指向這個名稱對應的參考
            advisorDef.getPropertyValues().add(POINTCUT, new RuntimeBeanReference((String) pointcut));
            parserContext.registerComponent(
                    new AdvisorComponentDefinition(advisorBeanName, advisorDef));
        }
    }
    finally {
        this.parseState.pop();
    }
}

決議程序大致如下:

  1. 決議 <aop:advisor /> 標簽,創建一個 DefaultBeanFactoryPointcutAdvisor 型別的 RootBeanDefinition 物件,并指定了 Advice

    private AbstractBeanDefinition createAdvisorBeanDefinition(Element advisorElement, ParserContext parserContext) {
        // <1> 創建一個 DefaultBeanFactoryPointcutAdvisor 型別的 RootBeanDefinition 物件
        RootBeanDefinition advisorDefinition = new RootBeanDefinition(DefaultBeanFactoryPointcutAdvisor.class);
        // <2> 設定來源
        advisorDefinition.setSource(parserContext.extractSource(advisorElement));
    
        // <3> 獲取 `advice-ref` 屬性配置,必須配置一個對應的 Advice
        String adviceRef = advisorElement.getAttribute(ADVICE_REF);
        if (!StringUtils.hasText(adviceRef)) {
            parserContext.getReaderContext().error(
                    "'advice-ref' attribute contains empty value.", advisorElement, this.parseState.snapshot());
        }
        else {
            // <4> 將 `advice-ref` 添加至 `adviceBeanName` 屬性,也就是指向這個 Advice 參考
            advisorDefinition.getPropertyValues().add(
                    ADVICE_BEAN_NAME, new RuntimeBeanNameReference(adviceRef));
        }
    
        // <5> 根據 `order` 配置為 RootBeanDefinition 設定優先級
        if (advisorElement.hasAttribute(ORDER_PROPERTY)) {
            advisorDefinition.getPropertyValues().add(
                    ORDER_PROPERTY, advisorElement.getAttribute(ORDER_PROPERTY));
        }
    
        // <6> 回傳剛創建的 RootBeanDefinition
        return advisorDefinition;
    }
    
  2. 獲取 id 屬性

  3. 注冊第 1 步創建的 RootBeanDefinition

    1. 如果 id 不為空,則取其作為名稱
    2. 否則,生成一個名稱,也就是 className
  4. 獲取這個 Advisor 對應的 Pointcut(也許就是一個 AspectJExpressionPointcut,也可能是參考的 Pointcut 的名稱)

    1. 如果是 AspectJExpressionPointcut,第 1 步創建的 RootBeanDefinition 添加 pointcut 屬性,指向這個 AspectJExpressionPointcut
    2. 否則,如果是一個參考的 Pointcut 的名稱,第 1 步創建的 RootBeanDefinition 添加 pointcut 屬性,指向這個名稱對應的參考

<aop:aspect />

<beans>
    <aop:aspectj-autoproxy/>
    <bean id="aspectXmlConfig" />
    <aop:config>
        <aop:aspect id="AspectXmlConfig" ref="aspectXmlConfig">
            <aop:pointcut id="anyPublicMethod" expression="execution(public * *(..))"/>
            <aop:around method="aroundAnyPublicMethod" pointcut-ref="anyPublicMethod"/>
            <aop:before method="beforeAnyPublicMethod" pointcut-ref="anyPublicMethod"/>
            <aop:before method="beforeAnyPublicMethod" pointcut="execution(public * *(..))"/>
            <aop:after method="finalizeAnyPublicMethod" pointcut-ref="anyPublicMethod"/>
            <aop:after-returning method="afterAnyPublicMethod" pointcut-ref="anyPublicMethod"/>
            <aop:after-throwing method="afterThrowingAnyPublicMethod" pointcut-ref="anyPublicMethod"/>
        </aop:aspect>
    </aop:config>
</beans>

處理程序在 parseAspect(..) 方法中,如下:

private void parseAspect(Element aspectElement, ParserContext parserContext) {
    // <1> 獲取 `id` 和 `ref` 屬性
    String aspectId = aspectElement.getAttribute(ID);
    String aspectName = aspectElement.getAttribute(REF);

    try {
        this.parseState.push(new AspectEntry(aspectId, aspectName));
        // <2> 定義兩個集合 `beanDefinitions`、`beanReferences`
        // 決議出來的 BeanDefinition
        List<BeanDefinition> beanDefinitions = new ArrayList<>();
        // 需要參考的 Bean
        List<BeanReference> beanReferences = new ArrayList<>();

        // <3> 獲取所有的 <aop:declare-parents /> 子標簽,遍歷進行處理
        List<Element> declareParents = DomUtils.getChildElementsByTagName(aspectElement, DECLARE_PARENTS);
        for (int i = METHOD_INDEX; i < declareParents.size(); i++) {
            Element declareParentsElement = declareParents.get(i);
            // <3.1> 決議 <aop:declare-parents /> 子標簽
            // 解析出 DeclareParentsAdvisor 物件,添加至 `beanDefinitions`
            beanDefinitions.add(parseDeclareParents(declareParentsElement, parserContext));
        }

        // We have to parse "advice" and all the advice kinds in one loop, to get the
        // ordering semantics right.
        // <4> 獲取 <aop:aspectj /> 所有的子節點,遍歷進行處理
        NodeList nodeList = aspectElement.getChildNodes();
        boolean adviceFoundAlready = false;
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            // <4.1> 如果是 <aop:around />、<aop:before />、<aop:after />、<aop:after-returning />、<aop:after-throwing /> 標簽,則進行處理
            if (isAdviceNode(node, parserContext)) {
                // <4.2> 如果第一次進來,那么就是配置了 Advice,則 `ref` 必須指定一個 Bean,因為這些 Advice 的 `method` 需要從這個 Bean 中獲取
                if (!adviceFoundAlready) {
                    adviceFoundAlready = true;
                    if (!StringUtils.hasText(aspectName)) {
                        parserContext.getReaderContext().error(
                                "<aspect> tag needs aspect bean reference via 'ref' attribute when declaring advices.",
                                aspectElement, this.parseState.snapshot());
                        return;
                    }
                    // <4.2.1> 往 `beanReferences` 添加需要參考的 Bean
                    beanReferences.add(new RuntimeBeanReference(aspectName));
                }
                // <4.3> 根據 Advice 標簽進行決議
                // 創建一個 AspectJPointcutAdvisor 物件,里面包含了 Advice 物件和對應的 Pointcut 物件,并進行注冊
                AbstractBeanDefinition advisorDefinition = parseAdvice(
                        aspectName, i, aspectElement, (Element) node, parserContext, beanDefinitions, beanReferences);
                // <4.4> 添加至 `beanDefinitions` 中
                beanDefinitions.add(advisorDefinition);
            }
        }

        // <5> 將上面創建的所有 Advisor 和參考物件都封裝到 AspectComponentDefinition 物件中
        // 并放入 `parserContext` 背景關系中,暫時忽略
        AspectComponentDefinition aspectComponentDefinition = createAspectComponentDefinition(
                aspectElement, aspectId, beanDefinitions, beanReferences, parserContext);
        parserContext.pushContainingComponent(aspectComponentDefinition);

        // <6> 獲取所有的 <aop:pointcut /> 子標簽,進行遍歷處理
        List<Element> pointcuts = DomUtils.getChildElementsByTagName(aspectElement, POINTCUT);
        for (Element pointcutElement : pointcuts) {
            // <6.1> 決議出 AspectJExpressionPointcut 物件并注冊
            parsePointcut(pointcutElement, parserContext);
        }
        parserContext.popAndRegisterContainingComponent();
    } finally {
        this.parseState.pop();
    }
}

決議程序大致如下:

  1. 獲取 idref 屬性
  2. 定義兩個集合 beanDefinitionsbeanReferences,分別保存決議出來的 BeanDefinition 和需要參考的 Bean
  3. 獲取所有的 <aop:declare-parents /> 子標簽,遍歷進行處理
    1. 決議 <aop:declare-parents /> 子標簽,決議出 DeclareParentsAdvisor 物件并注冊,添加至 beanDefinitions
  4. 獲取 <aop:aspectj /> 所有的子節點,遍歷進行處理
    1. 如果是 <aop:around />、<aop:before />、<aop:after />、<aop:after-returning />、<aop:after-throwing /> 標簽,則進行處理
    2. 如果第一次進來,那么就是配置了 Advice,則 ref 必須指定一個 Bean,因為這些 Advice 的 method 需要從這個 Bean 中獲取
      1. beanReferences 添加需要參考的 Bean
    3. 根據 Advice 標簽進行決議,創建一個 AspectJPointcutAdvisor 物件,里面包含了 Advice 物件和對應的 Pointcut 物件,并進行注冊
    4. 添加至 beanDefinitions
  5. 將上面創建的所有 Advisor 和參考物件都封裝到 AspectComponentDefinition 物件中,并放入 parserContext 背景關系中,暫時忽略
  6. 獲取所有的 <aop:pointcut /> 子標簽,進行遍歷處理
    1. 決議出 AspectJExpressionPointcut 物件并注冊,前面已經講過了

上面第 4.3 會決議相關 Advice 標簽,我們一起來看看

<aop:aspect /> 的 Advice 子標簽

private AbstractBeanDefinition parseAdvice(
        String aspectName, int order, Element aspectElement, Element adviceElement, ParserContext parserContext,
        List<BeanDefinition> beanDefinitions, List<BeanReference> beanReferences) {
    try {
        this.parseState.push(new AdviceEntry(parserContext.getDelegate().getLocalName(adviceElement)));

        // create the method factory bean
        // <1> 創建 MethodLocatingFactoryBean 型別的 RootBeanDefinition
        // 因為通過標簽配置的 Advice 對應的方法在其他 Bean 中,那么可以借助于 FactoryBean 來進行創建
        RootBeanDefinition methodDefinition = new RootBeanDefinition(MethodLocatingFactoryBean.class);
        // <1.1> 獲取 `targetBeanName` 和 `method` 并進行設定
        methodDefinition.getPropertyValues().add("targetBeanName", aspectName);
        methodDefinition.getPropertyValues().add("methodName", adviceElement.getAttribute("method"));
        // <1.2> 設定這個 Bean 是由 Spring 內部合成的
        methodDefinition.setSynthetic(true);

        // create instance factory definition
        // <2> 創建一個 SimpleBeanFactoryAwareAspectInstanceFactory 型別的 RootBeanDefinition
        RootBeanDefinition aspectFactoryDef = new RootBeanDefinition(SimpleBeanFactoryAwareAspectInstanceFactory.class);
        // <2.1> 設定了 AspectJ 對應的 名稱,用于獲取這個 AspectJ 的實體物件
        aspectFactoryDef.getPropertyValues().add("aspectBeanName", aspectName);
        // <2.2> 設定這個 Bean 是由 Spring 內部合成的
        aspectFactoryDef.setSynthetic(true);

        // register the pointcut
        // <3> 創建一個 Advice 物件,包含了對應的 Pointcut
        AbstractBeanDefinition adviceDef = createAdviceDefinition(
                adviceElement, parserContext, aspectName, order, methodDefinition, aspectFactoryDef,
                beanDefinitions, beanReferences);

        // configure the advisor
        // <4> 創建一個 AspectJPointcutAdvisor 型別的 RootBeanDefinition 物件,用于包裝上面創建的 Advice
        // Spring AOP 中的 Advice 都是放入 Advisor “容器” 中
        RootBeanDefinition advisorDefinition = new RootBeanDefinition(AspectJPointcutAdvisor.class);
        // <4.1> 設定來源
        advisorDefinition.setSource(parserContext.extractSource(adviceElement));
        // <4.2> 將上面創建的 Advice 物件作為構造器入參
        advisorDefinition.getConstructorArgumentValues().addGenericArgumentValue(adviceDef);
        // <4.3> 設定 `order` 優先級
        if (aspectElement.hasAttribute(ORDER_PROPERTY)) {
            advisorDefinition.getPropertyValues().add(
                    ORDER_PROPERTY, aspectElement.getAttribute(ORDER_PROPERTY));
        }

        // register the final advisor
        // <5> 注冊這個 AspectJPointcutAdvisor,自動生成名字
        parserContext.getReaderContext().registerWithGeneratedName(advisorDefinition);

        // <6> 回傳這個已注冊的 AspectJPointcutAdvisor
        return advisorDefinition;
    }
    finally {
        this.parseState.pop();
    }
}

處理程序大致如下:

  1. 創建 MethodLocatingFactoryBean 型別的 RootBeanDefinition,因為通過標簽配置的 Advice 對應的方法在其他 Bean 中,那么可以借助于 FactoryBean 來進行創建

    1. 獲取 targetBeanNamemethod 并進行設定
    2. 設定這個 Bean 是由 Spring 內部合成的
  2. 創建一個 SimpleBeanFactoryAwareAspectInstanceFactory 型別的 RootBeanDefinition

    1. 設定了 AspectJ 對應的 名稱,用于獲取這個 AspectJ 的實體物件
    2. 設定這個 Bean 是由 Spring 內部合成的
  3. 創建一個 Advice 物件,包含了對應的 Pointcut

    private AbstractBeanDefinition createAdviceDefinition(
            Element adviceElement, ParserContext parserContext, String aspectName, int order,
            RootBeanDefinition methodDef, RootBeanDefinition aspectFactoryDef,
            List<BeanDefinition> beanDefinitions, List<BeanReference> beanReferences) {
    
        // <1> 根據 Advice 標簽創建對應的 Advice
        // <aop:before /> -> AspectJMethodBeforeAdvice
        // <aop:after /> -> AspectJAfterAdvice
        // <aop:after-returning /> -> AspectJAfterReturningAdvice
        // <aop:after-throwing /> -> AspectJAfterThrowingAdvice
        // <aop:around /> -> AspectJAroundAdvice
        RootBeanDefinition adviceDefinition = new RootBeanDefinition(getAdviceClass(adviceElement, parserContext));
        // <1.1> 設定來源
        adviceDefinition.setSource(parserContext.extractSource(adviceElement));
        // <1.2> 設定參考的 AspectJ 的名稱
        adviceDefinition.getPropertyValues().add(ASPECT_NAME_PROPERTY, aspectName);
        // <1.3> 設定優先級
        adviceDefinition.getPropertyValues().add(DECLARATION_ORDER_PROPERTY, order);
    
        if (adviceElement.hasAttribute(RETURNING)) {
            adviceDefinition.getPropertyValues().add(
                    RETURNING_PROPERTY, adviceElement.getAttribute(RETURNING));
        }
        if (adviceElement.hasAttribute(THROWING)) {
            adviceDefinition.getPropertyValues().add(
                    THROWING_PROPERTY, adviceElement.getAttribute(THROWING));
        }
        if (adviceElement.hasAttribute(ARG_NAMES)) {
            adviceDefinition.getPropertyValues().add(
                    ARG_NAMES_PROPERTY, adviceElement.getAttribute(ARG_NAMES));
        }
    
        // <2> 獲取 Advice 的構造器引數物件 `cav`
        // 設定 1. 參考的方法、2. Pointcut(也許是參考的 Pointcut 的名稱)、3. 參考的方法所屬 AspectJ 物件
        // 你點進這些 Advice 型別的物件中看看構造方法就知道怎么回事,例如:AspectJMethodBeforeAdvice
        ConstructorArgumentValues cav = adviceDefinition.getConstructorArgumentValues();
        // <2.1> 往 `cav` 添加 Advice 對應的方法作為入參
        cav.addIndexedArgumentValue(METHOD_INDEX, methodDef);
    
        // <2.2> 決議出對應的 Pointcut 物件(可能是一個 AspectJExpressionPointcut,也可能是參考的 Pointcut 的一個運行時參考物件)
        Object pointcut = parsePointcutProperty(adviceElement, parserContext);
        // <2.2.1> 如果是 AspectJExpressionPointcut
        if (pointcut instanceof BeanDefinition) {
            // 往 `cav` 添加 `pointcut` 入參
            cav.addIndexedArgumentValue(POINTCUT_INDEX, pointcut);
            // 添加至 `beanDefinitions`
            beanDefinitions.add((BeanDefinition) pointcut);
        }
        // <2.2.2> 否則,如果是 參考的 Pointcut
        else if (pointcut instanceof String) {
            // 根據參考的 Pointcut 的名稱生成一個參考物件
            RuntimeBeanReference pointcutRef = new RuntimeBeanReference((String) pointcut);
            // 往構 `cav` 添加 `pointcut` 入參
            cav.addIndexedArgumentValue(POINTCUT_INDEX, pointcutRef);
            // 添加至 `pointcutRef`
            beanReferences.add(pointcutRef);
        }
    
        // <2.3> 往 `cav` 添加 Advice 對應的方法所在 Bean 作為入參
        cav.addIndexedArgumentValue(ASPECT_INSTANCE_FACTORY_INDEX, aspectFactoryDef);
    
        // <3> 回傳為 Advice 創建的 RootBeanDefinition 物件
        return adviceDefinition;
    }
    
    private Class<?> getAdviceClass(Element adviceElement, ParserContext parserContext) {
        String elementName = parserContext.getDelegate().getLocalName(adviceElement);
        if (BEFORE.equals(elementName)) {
            return AspectJMethodBeforeAdvice.class;
        }
        else if (AFTER.equals(elementName)) {
            return AspectJAfterAdvice.class;
        }
        else if (AFTER_RETURNING_ELEMENT.equals(elementName)) {
            return AspectJAfterReturningAdvice.class;
        }
        else if (AFTER_THROWING_ELEMENT.equals(elementName)) {
            return AspectJAfterThrowingAdvice.class;
        }
        else if (AROUND.equals(elementName)) {
            return AspectJAroundAdvice.class;
        }
        else {
            throw new IllegalArgumentException("Unknown advice kind [" + elementName + "].");
        }
    }
    
  4. 創建一個 AspectJPointcutAdvisor 型別的 RootBeanDefinition 物件,用于包裝上面創建的 Advice,Spring AOP 中的 Advice 都是放入 Advisor “容器” 中

  5. 注冊這個 AspectJPointcutAdvisor,自動生成名字

  6. 回傳這個已注冊的 AspectJPointcutAdvisor

------------------------------------

Spring Boot 注解驅動

在 Spring Boot 中使用 Spring AOP 我們通常會這樣進行 Maven 引入:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
    <version>2.3.5.RELEASE</version>
</dependency>

上面這個依賴內部會引入這樣兩個依賴:

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-aop</artifactId>
  <version>5.2.10.RELEASE</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjweaver</artifactId>
  <version>1.9.6</version>
  <scope>compile</scope>
</dependency>

引入相關依賴后,同樣可以使用 @EnableAspectJAutoProxy 注解來驅動整個 Spring AOP 依賴,不過在 Spring AOP 中你不需要顯示地使用這個注解,因為在 spring-boot-autoconfigure 中,有一個 AOP 自動配置類,我們一起來看看

AopAutoConfiguration

org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,Spring Boot 中的 AOP 自動配置類

@Configuration
@ConditionalOnClass({ EnableAspectJAutoProxy.class, Aspect.class, Advice.class, AnnotatedElement.class })
@ConditionalOnProperty(prefix = "spring.aop", name = "auto", havingValue = "https://www.cnblogs.com/lifullmoon/p/true", matchIfMissing = true)
public class AopAutoConfiguration {

	@Configuration
	@EnableAspectJAutoProxy(proxyTargetClass = false)
	@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "https://www.cnblogs.com/lifullmoon/p/false", matchIfMissing = false)
	public static class JdkDynamicAutoProxyConfiguration {

	}

	@Configuration
	@EnableAspectJAutoProxy(proxyTargetClass = true)
	@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "https://www.cnblogs.com/lifullmoon/p/true", matchIfMissing = true)
	public static class CglibAutoProxyConfiguration {

	}
}

可以看到這個 @Configuration 配置類中有兩個條件注解,都是基于 @Conditional 擴展的注解,如下:

  • @ConditionalOnClass 注解:value 中的所有 Class 物件在當前 JVM 必須存在才會注入當前配置類;

    因為你通過 Spring Boot 引入了 aspectjweaver 這個包,AspectAdviceAnnotatedElement 三個 Class 物件也就存在了,而 EnableAspectJAutoProxy 這個注解本身就存在 Spring 中,所以這個注解是滿足條件的

  • @ConditionalOnProperty 注解:指定的配置為 true 才會注入當前配置類

    這個注解會判斷 spring.aop.auto 是否為 true,沒有配置默認為 true,所以這個注解也是滿足條件的

所以得到的結論就是,當你引入 spring-boot-starter-aop 依賴后,Spring Boot 中會注入 AopAutoConfiguration 這個配置類,在這個配置類中的靜態內部類使用了 @EnableAspectJAutoProxy 這個注解,那么也就會注冊 Spring AOP 自動代理物件,

總結

通過本文,我們可以知道 @EnableAspectJAutoProxy 這個模塊驅動注解會借助 @Import 注解注冊一個 AnnotationAwareAspectJAutoProxyCreator 自動代理物件,也就開啟了 Spring AOP 自動代理,驅動了整個 Spring AOP 模塊,

除了注解的方式,Spring 一樣也支持 <aop:aspectj-autoproxy /> XML 配置的方式注冊一個自動代理物件,驅動整個 Spring AOP 模塊;也有 <aop:scoped-proxy /> 標簽支持裝飾某個 Bean,使其進行 AOP 代理,當然,Spring 也支持 <aop:config /> 標簽配置 AspectJ 切面的相關內容,包括 Poincut、Advice 和 Advisor 等配置,

同時,在使用 Spring Boot 中引入 spring-boot-starter-aop 依賴后,不需要顯示地使用 @EnableAspectJAutoProxy 注解來開啟 Spring AOP 的自動代理,因為在 spring-boot-autoconfigure 中,有一個 AopAutoConfiguration 自動配置類,會使用這個注解驅動了整個 Spring AOP 模塊,

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/279496.html

標籤:Java

上一篇:cmd中運行Java連接mysql資料庫,設定jar驅動

下一篇:Java編程語言學習-Java語言概述

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more