Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及)

admin2024-09-05  8

tx.xml事务配置文件的解析

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
    <context:property-placeholder location="classpath:dbconfig.properties"></context:property-placeholder>
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="driverClassName" value="${jdbc.driverClassName}"></property>
    </bean>
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" >
        <constructor-arg name="dataSource" ref="dataSource"></constructor-arg>
    </bean>
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <bean id="bookService" class="com.study.spring.tx.xml.service.BookService">
        <property name="bookDao" ref="bookDao"></property>
    </bean>
    <bean id="bookDao" class="com.study.spring.tx.xml.dao.BookDao">
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
    </bean>
    <aop:config>
        <aop:pointcut id="txPoint" expression="execution(* com.study.spring.tx.xml.*.*.*(..))"/>
        <aop:advisor advice-ref="myAdvice" pointcut-ref="txPoint"></aop:advisor>
    </aop:config>
    <tx:advice id="myAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="checkout" propagation="REQUIRED" />
            <tx:method name="updateStock" propagation="REQUIRES_NEW" />
        </tx:attributes>
    </tx:advice>
  <!--  <bean class="com.study.spring.MyBeanFactoryPostProcessorBySelf"></bean>-->
</beans>

PlaceholderConfigurerSupport类

spring提供的一个工具类,用于解析bean定义中属性值里面的占位符,此类不能被直接实例化使用
public abstract class PlaceholderConfigurerSupport extends PropertyResourceConfigurer
		implements BeanNameAware, BeanFactoryAware 

会把 > <context:property-placeholder location=“classpath:dbconfig.properties”></context:property-placeholder>
这个标签解析替换${jdbc.username}这样的内容

aop标签解析

    <aop:config>
        <aop:pointcut id="txPoint" expression="execution(* com.study.spring.tx.xml.*.*.*(..))"/>
        <aop:advisor advice-ref="myAdvice" pointcut-ref="txPoint"></aop:advisor>
    </aop:config>

根据标签名找到对应的handler
Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第1张

Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第2张

http\://www.springframework.org/schema/aop=org.springframework.aop.config.AopNamespaceHandler
AOP命名空间解析类。我们在用AOP的时候,会在Spring配置文件的beans标签中引入:xmlns:aop
public class AopNamespaceHandler extends NamespaceHandlerSupport {

	@Override
	public void init() {
		// In 2.0 XSD as well as in 2.5+ XSDs
		registerBeanDefinitionParser("config", new ConfigBeanDefinitionParser());
		registerBeanDefinitionParser("aspectj-autoproxy", new AspectJAutoProxyBeanDefinitionParser());
		registerBeanDefinitionDecorator("scoped-proxy", new ScopedProxyBeanDefinitionDecorator());

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

}
	/**解析自定义元素(在默认名称空间之外)。
	 * @param containingBd the containing bean definition (if any) @param containingBd包含bean的定义(如果有的话)
	 * @return the resulting bean definition 得到的bean定义
	 */
	@Nullable
	public BeanDefinition parseCustomElement(Element ele, @Nullable BeanDefinition containingBd) {
		// 获取对应的命名空间
		String namespaceUri = getNamespaceURI(ele);
		if (namespaceUri == null) {
			return null;
		}
		// 根据命名空间找到对应的NamespaceHandlerspring
		NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);
		if (handler == null) {
			error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", ele);
			return null;
		}
		// 调用自定义的NamespaceHandler进行解析 NamespaceHandlerSupport
		return handler.parse(ele, new ParserContext(this.readerContext, this, containingBd));
	}

handler.parse调用的是NamespaceHandlerSupport的parse方法,因为AopNamespaceHandler extends NamespaceHandlerSupport

	/**
	 * 通过委托为{@link Element}注册的{@link BeanDefinitionParser}来解析提供的{@link Element}。
	 */
	@Override
	@Nullable
	public BeanDefinition parse(Element element, ParserContext parserContext) {
		// 获取元素的解析器
		BeanDefinitionParser parser = findParserForElement(element, parserContext);
		return (parser != null ? parser.parse(element, parserContext) : null);//ComponentScanBeanDefinitionParser的方法
	}

parser是ConfigBeanDefinitionParser:

	public BeanDefinition parse(Element element, ParserContext parserContext) {
		CompositeComponentDefinition compositeDef =
				new CompositeComponentDefinition(element.getTagName(), parserContext.extractSource(element));
		parserContext.pushContainingComponent(compositeDef);
// 注册自动代理模式创建器,AspectjAwareAdvisorAutoProxyCreator 配置文件注解混合使用 context:commponentScan 注入innteral的类 这里也注入类似的类
		configureAutoProxyCreator(parserContext, element);
		List<Element> childElts = DomUtils.getChildElements(element);
		for (Element elt: childElts) {
			String localName = parserContext.getDelegate().getLocalName(elt);
			if (POINTCUT.equals(localName)) {
				parsePointcut(elt, parserContext);
			}
			else if (ADVISOR.equals(localName)) {
				parseAdvisor(elt, parserContext);
			}
			else if (ASPECT.equals(localName)) {
				parseAspect(elt, parserContext);
			}
		}

		parserContext.popAndRegisterContainingComponent();
		return null;
	}

configureAutoProxyCreator(parserContext, element);的功能是AspectJAwareAdvisorAutoProxyCreator引入。

pointcut 和 advisor 标签会在parsePointcut(elt, parserContext);和parseAdvisor(elt, parserContext);方法解析生成bean对象。
**parsePointcut(elt, parserContext);**最终createPointcutDefinition:

	/**
	 * Creates a {@link BeanDefinition} for the {@link AspectJExpressionPointcut} class using
	 * the supplied pointcut expression.
	 */
	protected AbstractBeanDefinition createPointcutDefinition(String expression) {
		RootBeanDefinition beanDefinition = new RootBeanDefinition(AspectJExpressionPointcut.class);
		beanDefinition.setScope(BeanDefinition.SCOPE_PROTOTYPE);
		beanDefinition.setSynthetic(true);
		beanDefinition.getPropertyValues().add(EXPRESSION, expression);
		return beanDefinition;
	}
<aop:pointcut id="txPoint" expression="execution(* com.study.spring.tx.xml.*.*.*(..))"/>对应AspectJExpressionPointcut

**parseAdvisor(elt, parserContext);**最终调用createAdvisorBeanDefinition:

	/**
	 * 解析advisor顾问类
	 *
	 * Parses the supplied {@code <advisor>} element and registers the resulting
	 * {@link org.springframework.aop.Advisor} and any resulting {@link org.springframework.aop.Pointcut}
	 * with the supplied {@link BeanDefinitionRegistry}.
	 */
	private void parseAdvisor(Element advisorElement, ParserContext parserContext) {
		// 解析<aop:advisor>节点,最终创建的beanClass为`DefaultBeanFactoryPointcutAdvisor`
		// 另外advice-ref属性必须定义,其与内部属性adviceBeanName对应
		AbstractBeanDefinition advisorDef = createAdvisorBeanDefinition(advisorElement, parserContext);
		String id = advisorElement.getAttribute(ID);

		try {
			// 注册到bean工厂
			this.parseState.push(new AdvisorEntry(id));
			String advisorBeanName = id;
			if (StringUtils.hasText(advisorBeanName)) {
				parserContext.getRegistry().registerBeanDefinition(advisorBeanName, advisorDef);
			}
			else {
				advisorBeanName = parserContext.getReaderContext().registerWithGeneratedName(advisorDef);
			}

			// 解析point-cut属性并赋值到DefaultBeanFactoryPointcutAdvisor#pointcut内部属性
			Object pointcut = parsePointcutProperty(advisorElement, parserContext);
			if (pointcut instanceof BeanDefinition) {
				advisorDef.getPropertyValues().add(POINTCUT, pointcut);
				parserContext.registerComponent(
						new AdvisorComponentDefinition(advisorBeanName, advisorDef, (BeanDefinition) pointcut));
			}
			else if (pointcut instanceof String) {
				advisorDef.getPropertyValues().add(POINTCUT, new RuntimeBeanReference((String) pointcut));
				parserContext.registerComponent(
						new AdvisorComponentDefinition(advisorBeanName, advisorDef));
			}
		}
		finally {
			this.parseState.pop();
		}
	}

	/**
	 * Create a {@link RootBeanDefinition} for the advisor described in the supplied. Does <strong>not</strong>
	 * parse any associated '{@code pointcut}' or '{@code pointcut-ref}' attributes.
	 */
	private AbstractBeanDefinition createAdvisorBeanDefinition(Element advisorElement, ParserContext parserContext) {
		RootBeanDefinition advisorDefinition = new RootBeanDefinition(DefaultBeanFactoryPointcutAdvisor.class);
		advisorDefinition.setSource(parserContext.extractSource(advisorElement));

		String adviceRef = advisorElement.getAttribute(ADVICE_REF);
		if (!StringUtils.hasText(adviceRef)) {
			parserContext.getReaderContext().error(
					"'advice-ref' attribute contains empty value.", advisorElement, this.parseState.snapshot());
		}
		else {
			advisorDefinition.getPropertyValues().add(
					ADVICE_BEAN_NAME, new RuntimeBeanNameReference(adviceRef));
		}

		if (advisorElement.hasAttribute(ORDER_PROPERTY)) {
			advisorDefinition.getPropertyValues().add(
					ORDER_PROPERTY, advisorElement.getAttribute(ORDER_PROPERTY));
		}

		return advisorDefinition;
	}
<aop:advisor advice-ref="myAdvice" pointcut-ref="txPoint"></aop:advisor>对应DefaultBeanFactoryPointcutAdvisor.class

tx事务标签解析

    <tx:advice id="myAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="checkout" propagation="REQUIRED" />
            <tx:method name="updateStock" propagation="REQUIRES_NEW" />
        </tx:attributes>
    </tx:advice>

根据标签名找到对应的handler
Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第1张
Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第4张

http\://www.springframework.org/schema/tx=org.springframework.transaction.config.TxNamespaceHandler

public class TxNamespaceHandler extends NamespaceHandlerSupport {

	static final String TRANSACTION_MANAGER_ATTRIBUTE = "transaction-manager";

	static final String DEFAULT_TRANSACTION_MANAGER_BEAN_NAME = "transactionManager";


	static String getTransactionManagerName(Element element) {
		return (element.hasAttribute(TRANSACTION_MANAGER_ATTRIBUTE) ?
				element.getAttribute(TRANSACTION_MANAGER_ATTRIBUTE) : DEFAULT_TRANSACTION_MANAGER_BEAN_NAME);
	}


	@Override
	public void init() {
			// 注册不同的xml文件标签解析器
		registerBeanDefinitionParser("advice", new TxAdviceBeanDefinitionParser());
		registerBeanDefinitionParser("annotation-driven", new AnnotationDrivenBeanDefinitionParser());
		registerBeanDefinitionParser("jta-transaction-manager", new JtaTransactionManagerBeanDefinitionParser());
	}

}
		/**解析自定义元素(在默认名称空间之外)。
	 * @param containingBd the containing bean definition (if any) @param containingBd包含bean的定义(如果有的话)
	 * @return the resulting bean definition 得到的bean定义
	 */
	@Nullable
	public BeanDefinition parseCustomElement(Element ele, @Nullable BeanDefinition containingBd) {
		// 获取对应的命名空间
		String namespaceUri = getNamespaceURI(ele);
		if (namespaceUri == null) {
			return null;
		}
		// 根据命名空间找到对应的NamespaceHandlerspring
		NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);
		if (handler == null) {
			error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", ele);
			return null;
		}
		// 调用自定义的NamespaceHandler进行解析 NamespaceHandlerSupport
		return handler.parse(ele, new ParserContext(this.readerContext, this, containingBd));
	}

handler.parse调用的是NamespaceHandlerSupport的parse方法,因为 TxNamespaceHandler extends NamespaceHandlerSupport

	/**
	 * 通过委托为{@link Element}注册的{@link BeanDefinitionParser}来解析提供的{@link Element}。
	 */
	@Override
	@Nullable
	public BeanDefinition parse(Element element, ParserContext parserContext) {
		// 获取元素的解析器
		BeanDefinitionParser parser = findParserForElement(element, parserContext);
		return (parser != null ? parser.parse(element, parserContext) : null);//ComponentScanBeanDefinitionParser的方法
	}

parser是AbstractBeanDefinitionParser

		@Override
	@Nullable
	public final BeanDefinition parse(Element element, ParserContext parserContext) {
		AbstractBeanDefinition definition = parseInternal(element, parserContext);
		if (definition != null && !parserContext.isNested()) {
			try {
				String id = resolveId(element, definition, parserContext);
				if (!StringUtils.hasText(id)) {
					parserContext.getReaderContext().error(
							"Id is required for element '" + parserContext.getDelegate().getLocalName(element)
									+ "' when used as a top-level tag", element);
				}
				String[] aliases = null;
				if (shouldParseNameAsAliases()) {
					String name = element.getAttribute(NAME_ATTRIBUTE);
					if (StringUtils.hasLength(name)) {
						aliases = StringUtils.trimArrayElements(StringUtils.commaDelimitedListToStringArray(name));
					}
				}
				// 将AbstractBeanDefinition转换为BeanDefinitionHolder并注册
				BeanDefinitionHolder holder = new BeanDefinitionHolder(definition, id, aliases);
				registerBeanDefinition(holder, parserContext.getRegistry());
				if (shouldFireEvents()) {
					// 通知监听器进行处理
					BeanComponentDefinition componentDefinition = new BeanComponentDefinition(holder);
					postProcessComponentDefinition(componentDefinition);
					parserContext.registerComponent(componentDefinition);
				}
			}
			catch (BeanDefinitionStoreException ex) {
				String msg = ex.getMessage();
				parserContext.getReaderContext().error((msg != null ? msg : ex.toString()), element);
				return null;
			}
		}
		return definition;
	}

parseInternal(element, parserContext);是AbstractSingleBeanDefinitionParser的parseInternal方法

	@Override
	protected final AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
		BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition();
		String parentName = getParentName(element);
		if (parentName != null) {
			builder.getRawBeanDefinition().setParentName(parentName);
		}
		// 获取自定义标签中的class,此时会调用自定义解析器
		Class<?> beanClass = getBeanClass(element);
		if (beanClass != null) {
			builder.getRawBeanDefinition().setBeanClass(beanClass);
		}
		else {
			// 若子类没有重写getBeanClass方法则尝试检查子类是否重写getBeanClassName方法
			String beanClassName = getBeanClassName(element);
			if (beanClassName != null) {
				builder.getRawBeanDefinition().setBeanClassName(beanClassName);
			}
		}
		builder.getRawBeanDefinition().setSource(parserContext.extractSource(element));
		BeanDefinition containingBd = parserContext.getContainingBeanDefinition();
		if (containingBd != null) {
			// Inner bean definition must receive same scope as containing bean.
			// 若存在父类则使用父类的scope属性
			builder.setScope(containingBd.getScope());
		}
		if (parserContext.isDefaultLazyInit()) {
			// Default-lazy-init applies to custom bean definitions as well.
			// 配置延迟加载
			builder.setLazyInit(true);
		}
		// 调用子类重写的doParse方法进行解析
		doParse(element, parserContext, builder);
		return builder.getBeanDefinition();
	}

Class<?> beanClass = getBeanClass(element);调用的是TxAdviceBeanDefinitionParser的方法:

	@Override
	protected Class<?> getBeanClass(Element element) {
		return TransactionInterceptor.class;
	}

TransactionInterceptor

//事务拦截器,实现了方法拦截器MethodInterceptor
public class TransactionInterceptor extends TransactionAspectSupport implements MethodInterceptor, Serializable {
	@Override
	@Nullable
	public Object invoke(MethodInvocation invocation) throws Throwable {
		// Work out the target class: may be {@code null}.
		// The TransactionAttributeSource should be passed the target class
		// as well as the method, which may be from an interface.
		// 获取我们的代理对象的class属性
		Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);

		// Adapt to TransactionAspectSupport's invokeWithinTransaction...
		/**
		 * 以事务的方式调用目标方法
		 * 在这埋了一个钩子函数 用来回调目标方法的
		 */
		return invokeWithinTransaction(invocation.getMethod(), targetClass, invocation::proceed);
	}
}

// 调用子类重写的doParse方法进行解析
doParse(element, parserContext, builder);

TxAdviceBeanDefinitionParser的doParse方法:

	@Override
	protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {//<tx:advice标签有transaction-manager就取标签没有就取默认的DEFAULT_TRANSACTION_MANAGER_BEAN_NAME = "transactionManager";
		builder.addPropertyReference("transactionManager", TxNamespaceHandler.getTransactionManagerName(element));//<tx:advice id="myAdvice" transaction-manager="transactionManager">

		List<Element> txAttributes = DomUtils.getChildElementsByTagName(element, ATTRIBUTES_ELEMENT);
		if (txAttributes.size() > 1) {
			parserContext.getReaderContext().error(
					"Element <attributes> is allowed at most once inside element <advice>", element);
		}
		else if (txAttributes.size() == 1) {
			// Using attributes source.
			Element attributeSourceElement = txAttributes.get(0);
			RootBeanDefinition attributeSourceDefinition = parseAttributeSource(attributeSourceElement, parserContext);
			builder.addPropertyValue("transactionAttributeSource", attributeSourceDefinition);
		}
		else {
			// Assume annotations source.
			builder.addPropertyValue("transactionAttributeSource",
					new RootBeanDefinition("org.springframework.transaction.annotation.AnnotationTransactionAttributeSource"));
		}
	}

TxAdviceBeanDefinitionParser的parseAttributeSource方法:

private RootBeanDefinition parseAttributeSource(Element attrEle, ParserContext parserContext) {
		List<Element> methods = DomUtils.getChildElementsByTagName(attrEle, METHOD_ELEMENT);
		ManagedMap<TypedStringValue, RuleBasedTransactionAttribute> transactionAttributeMap =
				new ManagedMap<>(methods.size());
		transactionAttributeMap.setSource(parserContext.extractSource(attrEle));

		for (Element methodEle : methods) {
			String name = methodEle.getAttribute(METHOD_NAME_ATTRIBUTE);
			TypedStringValue nameHolder = new TypedStringValue(name);
			nameHolder.setSource(parserContext.extractSource(methodEle));

			RuleBasedTransactionAttribute attribute = new RuleBasedTransactionAttribute();
			String propagation = methodEle.getAttribute(PROPAGATION_ATTRIBUTE);
			String isolation = methodEle.getAttribute(ISOLATION_ATTRIBUTE);
			String timeout = methodEle.getAttribute(TIMEOUT_ATTRIBUTE);
			String readOnly = methodEle.getAttribute(READ_ONLY_ATTRIBUTE);
			if (StringUtils.hasText(propagation)) {
				attribute.setPropagationBehaviorName(RuleBasedTransactionAttribute.PREFIX_PROPAGATION + propagation);
			}
			if (StringUtils.hasText(isolation)) {
				attribute.setIsolationLevelName(RuleBasedTransactionAttribute.PREFIX_ISOLATION + isolation);
			}
			if (StringUtils.hasText(timeout)) {
				try {
					attribute.setTimeout(Integer.parseInt(timeout));
				}
				catch (NumberFormatException ex) {
					parserContext.getReaderContext().error("Timeout must be an integer value: [" + timeout + "]", methodEle);
				}
			}
			if (StringUtils.hasText(readOnly)) {
				attribute.setReadOnly(Boolean.parseBoolean(methodEle.getAttribute(READ_ONLY_ATTRIBUTE)));
			}

			List<RollbackRuleAttribute> rollbackRules = new ArrayList<>(1);
			if (methodEle.hasAttribute(ROLLBACK_FOR_ATTRIBUTE)) {
				String rollbackForValue = methodEle.getAttribute(ROLLBACK_FOR_ATTRIBUTE);
				addRollbackRuleAttributesTo(rollbackRules, rollbackForValue);
			}
			if (methodEle.hasAttribute(NO_ROLLBACK_FOR_ATTRIBUTE)) {
				String noRollbackForValue = methodEle.getAttribute(NO_ROLLBACK_FOR_ATTRIBUTE);
				addNoRollbackRuleAttributesTo(rollbackRules, noRollbackForValue);
			}
			attribute.setRollbackRules(rollbackRules);

			transactionAttributeMap.put(nameHolder, attribute);
		}

		RootBeanDefinition attributeSourceDefinition = new RootBeanDefinition(NameMatchTransactionAttributeSource.class);
		attributeSourceDefinition.setSource(parserContext.extractSource(attrEle));
		attributeSourceDefinition.getPropertyValues().add("nameMap", transactionAttributeMap);
		return attributeSourceDefinition;
	}

    <tx:attributes>
        <tx:method name="checkout" propagation="REQUIRED" />
        <tx:method name="updateStock" propagation="REQUIRES_NEW" />
    </tx:attributes>

上述方法解析这些事务相关的标签,隔离级别、传播特性、超时时间、是否可读。这几个属性如果标签有设置就取没设置就用默认值。
Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第5张
方法最终返回了一个RootBeanDefinition,class是NameMatchTransactionAttributeSource.class
Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第6张

这一步完成,tx.xml文件的标签就解析完成,此时生成事务相关的如下:
Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第7张

此时befactory中bean定义信息如下:
Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第8张

Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第9张

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="driverClassName" value="${jdbc.driverClassName}"></property>
    </bean>

上面的属性值还是${jdbc.username}变量接下来要进行替换,在invokeBeanFactoryPostProcessors(beanFactory);方法中执行。调用PropertySourcesPlaceholderConfigurer类的方法
Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第10张
invokeBeanFactoryPostProcessors执行结束之后:
Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第11张
Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第12张
registerBeanPostProcessors方法执行结束之后:
AspectJAwareAdvisorAutoProxyCreator对象生成在一级缓存:
Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第13张因为class AspectJAwareAdvisorAutoProxyCreator extends AbstractAdvisorAutoProxyCreator

public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyCreator 
public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport
		implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware 
 interface SmartInstantiationAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessor 
interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor 

相关对象的创建

对象的创建有如下几种方式:
Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第14张

接下来开始讲解存储在bean定义信息map里的十个对象的循环创建过程:以dataSource为例,

findAdvisorBeans:75, BeanFactoryAdvisorRetrievalHelper (org.springframework.aop.framework.autoproxy)
findCandidateAdvisors:111, AbstractAdvisorAutoProxyCreator (org.springframework.aop.framework.autoproxy)
shouldSkip:101, AspectJAwareAdvisorAutoProxyCreator (org.springframework.aop.aspectj.autoproxy)
postProcessBeforeInstantiation:252, AbstractAutoProxyCreator (org.springframework.aop.framework.autoproxy)
applyBeanPostProcessorsBeforeInstantiation:1145, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
resolveBeforeInstantiation:1118, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
createBean:505, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
lambda$doGetBean(:324, AbstractBeanFactory )org.springframework.beans.factory.support200404000
getObject:-1, ( $$org.springframework.beans.factory.support.AbstractBeanFactoryLambda)(
getSingleton:234, DefaultSingletonBeanRegistry )org.springframework.beans.factory.support(
doGetBean:322, AbstractBeanFactory )org.springframework.beans.factory.support(
getBean:202, AbstractBeanFactory )org.springframework.beans.factory.support(
preInstantiateSingletons:897, DefaultListableBeanFactory )org.springframework.beans.factory.support(
finishBeanFactoryInitialization:879, AbstractApplicationContext )org.springframework.context.support(
refresh:551, AbstractApplicationContext )org.springframework.context.support<
>init(:144, ClassPathXmlApplicationContext )org.springframework.context.support<
>init(:85, ClassPathXmlApplicationContext )org.springframework.context.support(
main:15, TxTest )com.study.spring.tx.xmlapplyBeanPostProcessorsBeforeInstantiation

protected

	Object applyBeanPostProcessorsBeforeInstantiation (Class<?>, beanClassString ) beanNamefor {
		( BeanPostProcessor: bp getBeanPostProcessors ())if {
			( instanceofbp InstantiationAwareBeanPostProcessor )InstantiationAwareBeanPostProcessor {
				= ibp ( InstantiationAwareBeanPostProcessor); bpObject
				= result . ibppostProcessBeforeInstantiation(,beanClass) beanName;if
				( !=result null )return {
					; result}
				}
			}
		return
		null ;}
	postProcessBeforeInstantiation:252, AbstractAutoProxyCreator (org.springframework.aop.framework.autoproxy)

AbstractAdvisorAutoProxyCreator 类最终extends InstantiationAwareBeanPostProcessor 所以会进入调用postProcessBeforeInstantiation,才有了findAdvisorBeans
/** * Find all eligible Advisor beans in the current bean factory, * ignoring FactoryBeans and excluding beans that are currently in creation. * @return the list of {@link org.springframework.aop.Advisor} beans * @see #isEligibleBean */
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, Advisor.class, true, false);这个方法找到Advisor子类:org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0并返回
Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第15张

	public
	List <Advisor>findAdvisorBeans ()// Determine list of advisor bean names, if not cached already. {
		String
		[]= advisorNames this .;cachedAdvisorBeanNamesif
		( ==advisorNames null )// Do not initialize FactoryBeans here: We need to leave all regular beans {
			// uninitialized to let the auto-proxy creator apply to them!
			=
			advisorNames BeanFactoryUtils .beanNamesForTypeIncludingAncestors(this
					.,beanFactoryAdvisor .class,true ,false );this
			.=cachedAdvisorBeanNames ; advisorNames}
		if
		( .advisorNames==length 0 )return {
			new ArrayList <>();}
		List

		<Advisor>= advisors new ArrayList <>();for
		( String: name ) advisorNamesif {
			( isEligibleBean()name)if {
				( this..beanFactoryisCurrentlyInCreation()name)if {
					( .loggerisTraceEnabled()). {
						loggertrace("Skipping currently created advisor '"+ + name "'" );}
					}
				else
				try {
					. {
						advisorsadd(this..beanFactorygetBean(,nameAdvisor .class));}
					catch
					( BeanCreationException) exThrowable {
						= rootCause . exgetMostSpecificCause();if
						( instanceofrootCause BeanCurrentlyInCreationException )BeanCreationException {
							= bce ( BeanCreationException); rootCauseString
							= bceBeanName . bcegetBeanName();if
							( !=bceBeanName null && this ..beanFactoryisCurrentlyInCreation()bceBeanName)if {
								( .loggerisTraceEnabled()). {
									loggertrace("Skipping advisor '"+ + name "' with dependency on currently created bean: "
											+ . exgetMessage());}
								// Ignore: indicates a reference back to the bean we're trying to advise.
								// We want to find advisors other than the currently created bean itself.
								continue
								;}
							}
						throw
						; ex}
					}
				}
			}
		return
		; advisors}
	实例化DefaultBeanFactoryPointcutAdvisor

.

advisorsadd(this..beanFactorygetBean(,nameAdvisor .class));DefaultBeanFactoryPointcutAdvisor开始实例化(

创建实例化DefaultBeanFactoryPointcutAdvisor对象的流程:

doCreateBean:559, AbstractAutowireCapableBeanFactory )org.springframework.beans.factory.support(
createBean:516, AbstractAutowireCapableBeanFactory )org.springframework.beans.factory.support$doGetBean
lambda():324, AbstractBeanFactory 200404000org.springframework.beans.factory.support(
getObject:-1, $$ org.springframework.beans.factory.support.AbstractBeanFactory)Lambda()
getSingleton:234, DefaultSingletonBeanRegistry (org.springframework.beans.factory.support)
doGetBean:322, AbstractBeanFactory (org.springframework.beans.factory.support)
getBean:207, AbstractBeanFactory (org.springframework.beans.factory.support)
findAdvisorBeans:91, BeanFactoryAdvisorRetrievalHelper (org.springframework.aop.framework.autoproxy)
findCandidateAdvisors:111, AbstractAdvisorAutoProxyCreator (org.springframework.aop.framework.autoproxy)
shouldSkip:101, AspectJAwareAdvisorAutoProxyCreator (org.springframework.aop.aspectj.autoproxy)
postProcessBeforeInstantiation:252, AbstractAutoProxyCreator (org.springframework.aop.framework.autoproxy)
applyBeanPostProcessorsBeforeInstantiation:1145, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
resolveBeforeInstantiation:1118, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
createBean:505, AbstractAutowireCapableBeanFactory $doGetBeanorg.springframework.beans.factory.support(
lambda)200404000:324, AbstractBeanFactory (org.springframework.beans.factory.support$$
getObject:-1,  )org.springframework.beans.factory.support.AbstractBeanFactory(Lambda)(
getSingleton:234, DefaultSingletonBeanRegistry )org.springframework.beans.factory.support(
doGetBean:322, AbstractBeanFactory )org.springframework.beans.factory.support(
getBean:202, AbstractBeanFactory )org.springframework.beans.factory.support(
preInstantiateSingletons:897, DefaultListableBeanFactory )org.springframework.beans.factory.support(
finishBeanFactoryInitialization:879, AbstractApplicationContext )org.springframework.context.support<
refresh:551, AbstractApplicationContext >org.springframework.context.support(
)init<:144, ClassPathXmlApplicationContext >org.springframework.context.support(
)init(:85, ClassPathXmlApplicationContext )org.springframework.context.support(
main:15, TxTest )com.study.spring.tx.xml(

Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第16张
此时只创建对象没有进行属性填充,

populateBean:1400, AbstractAutowireCapableBeanFactory )org.springframework.beans.factory.support(
doCreateBean:593, AbstractAutowireCapableBeanFactory )org.springframework.beans.factory.support$doGetBean
createBean:516, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
lambda200404000(:324, AbstractBeanFactory $$org.springframework.beans.factory.support
getObject:-1, ) (org.springframework.beans.factory.support.AbstractBeanFactory)Lambda()
getSingleton:234, DefaultSingletonBeanRegistry (org.springframework.beans.factory.support)
doGetBean:322, AbstractBeanFactory (org.springframework.beans.factory.support)
getBean:207, AbstractBeanFactory (org.springframework.beans.factory.support)
findAdvisorBeans:91, BeanFactoryAdvisorRetrievalHelper (org.springframework.aop.framework.autoproxy)
findCandidateAdvisors:111, AbstractAdvisorAutoProxyCreator (org.springframework.aop.framework.autoproxy)
shouldSkip:101, AspectJAwareAdvisorAutoProxyCreator (org.springframework.aop.aspectj.autoproxy)
postProcessBeforeInstantiation:252, AbstractAutoProxyCreator (org.springframework.aop.framework.autoproxy)
applyBeanPostProcessorsBeforeInstantiation:1145, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
resolveBeforeInstantiation:1118, AbstractAutowireCapableBeanFactory $doGetBeanorg.springframework.beans.factory.support(
createBean:505, AbstractAutowireCapableBeanFactory )org.springframework.beans.factory.support200404000
lambda($$:324, AbstractBeanFactory org.springframework.beans.factory.support)
getObject:-1, ( )org.springframework.beans.factory.support.AbstractBeanFactory(Lambda)(
getSingleton:234, DefaultSingletonBeanRegistry )org.springframework.beans.factory.support(
doGetBean:322, AbstractBeanFactory )org.springframework.beans.factory.support(
getBean:202, AbstractBeanFactory )org.springframework.beans.factory.support(
preInstantiateSingletons:897, DefaultListableBeanFactory )org.springframework.beans.factory.support<
finishBeanFactoryInitialization:879, AbstractApplicationContext >org.springframework.context.support(
refresh:551, AbstractApplicationContext )org.springframework.context.support<
>init(:144, ClassPathXmlApplicationContext )org.springframework.context.support(
)init <aop:config> <aop:pointcut id="txPoint" expression="execution(* com.study.spring.tx.xml.*.*.*(..))"/> <aop:advisor advice-ref="myAdvice" pointcut-ref="txPoint"></aop:advisor> </aop:config>:85, ClassPathXmlApplicationContext protectedorg.springframework.context.supportvoid
main:15, TxTest populateBeancom.study.spring.tx.xml(

Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第17张
获取到需要填充的属性在这里和String对应

, RootBeanDefinition ,@NullableBeanWrapper beanName) if mbd( != null bw) {
	applyPropertyValues (pvs , ,, {
			);beanName} mbd} bwprotected pvsvoidapplyPropertyValues
		(
String
, BeanDefinition ,BeanWrapper, beanNamePropertyValues ) mbdfor ( bwPropertyValue : pvs) {


if (. pv isConverted original( {
			) )pv.add(); {
				deepCopy}elseStringpv=.
			getName
			( {
				) propertyName ; pvObject=.getValue(
				) originalValue ; pvif(==AutowiredPropertyMarker.
				INSTANCE )originalValue Method =.getPropertyDescriptor( {
					) writeMethod . bwgetWriteMethod()propertyName;if(==null)
					throw newwriteMethod IllegalArgumentException ("Autowire marker for property without write method: " {
						+ ) ;}= new pvDependencyDescriptor(
					new
					originalValue MethodParameter ( ,0) ,truewriteMethod) ;}Object =.resolveValueIfNecessary
				(
				, resolvedValue ) valueResolver;Object=pv; originalValueboolean=
				. convertedValue isWritableProperty resolvedValue(
				) convertible && bw!PropertyAccessorUtils.propertyNameisNestedOrIndexedProperty (
						);if()propertyName=convertForProperty
				( ,convertible, {
					convertedValue , );resolvedValue} propertyName// Possibly store converted value in merged bean definition, bw// in order to avoid re-conversion for every created bean instance. converterif(
				==
				)
				if
				( )resolvedValue . originalValuesetConvertedValue {
					( )convertible; {
						pv}.addconvertedValue()
					;
					deepCopy}elseifpv(&&
				instanceof
				TypedStringValue && !convertible ( originalValue ( TypedStringValue )
						).isDynamic() originalValue&&!(instanceofCollection ||
						ObjectUtils.convertedValue isArray ( ) )).setConvertedValueconvertedValue(); {
					pv.add(convertedValue);
					deepCopy}else=pvtrue;
				.
				add {
					resolveNecessary ( newPropertyValue
					deepCopy(,)) ;}pv} convertedValue}}resolveValueIfNecessary方法:
				/**
	 * Given a PropertyValue, return a value, resolving any references to other
	 * beans in the factory if necessary. The value could be:
	 * <li>A BeanDefinition, which leads to the creation of a corresponding
	 * new bean instance. Singleton flags and names of such "inner beans"
	 * are always ignored: Inner beans are anonymous prototypes.
	 * <li>A RuntimeBeanReference, which must be resolved.
	 * <li>A ManagedList. This is a special collection that may contain
	 * RuntimeBeanReferences or Collections that will need to be resolved.
	 * <li>A ManagedSet. May also contain RuntimeBeanReferences or
	 * Collections that will need to be resolved.
	 * <li>A ManagedMap. In this case the value may be a RuntimeBeanReference
	 * or Collection that will need to be resolved.
	 * <li>An ordinary object or {@code null}, in which case it's left alone.
	 * @param argName the name of the argument that the value is defined for
	 * @param value the value object to resolve
	 * @return the resolved object
	 */
			@Nullable
		public

Object

Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第18张
resolveValueIfNecessary

	(
	Object
	, @Nullable Object)// We must check each value to see whether it requires a runtime reference argName// to another bean to be resolved. if ( valueinstanceof {
		RuntimeBeanReference
		)
		RuntimeBeanReference =value ( RuntimeBeanReference) {
			; ref return resolveReference(, value)
			; }elseargNameif ref(instanceof
		RuntimeBeanNameReference
		) String =value ( (RuntimeBeanNameReference {
			) refName ) .getBeanName() value;=String.valueOf(
			refName doEvaluate ());if(refName!this.
			. containsBean())beanFactorythrownewBeanDefinitionStoreExceptionrefName("Invalid bean name '" {
				+ + "' in bean reference for "+
						) ; refName } return ; argName}else
			if
			( refNameinstanceof
		BeanDefinitionHolder
		) // Resolve BeanDefinitionHolder: contains BeanDefinition with name and aliases. BeanDefinitionHoldervalue = (BeanDefinitionHolder {
			)
			; bdHolder return resolveInnerBean(, value.
			getBeanName ()argName, bdHolder.getBeanDefinition()) bdHolder;}elseif(instanceof
		BeanDefinition
		) // Resolve plain BeanDefinition, without contained name: use dummy name. BeanDefinitionvalue = (BeanDefinition {
			)
			; bd String ="(inner bean)"+ valueBeanFactoryUtils
			. innerBeanName GENERATED_BEAN_NAME_SEPARATOR + ObjectUtils .getIdentityHexString( )
					;returnresolveInnerBean(bd,,
			) ;}argNameelse innerBeanNameif bd(instanceof
		DependencyDescriptor
		) Set <value String >= {
			newLinkedHashSet<> autowiredBeanNames ( 4 );Object=this..
			resolveDependency result ( (DependencyDescriptorbeanFactory),this
					.,, valuethis .)beanName; autowiredBeanNamesfor (StringtypeConverter:)
			if (this autowiredBeanName . autowiredBeanNames. {
				containsBean ())beanFactorythis..autowiredBeanNameregisterDependentBean( {
					,thisbeanFactory.);autowiredBeanName} }returnbeanName;}
				else
			if
			( resultinstanceof
		ManagedArray
		) // May need to resolve contained runtime references. ManagedArrayvalue = (ManagedArray {
			)
			; array Class <?> value=
			.;if( elementType == arraynullresolvedElementType)
			String =elementType . getElementTypeName( {
				) elementTypeName ; arrayif(StringUtils.hasText
				( ))try=ClassUtilselementTypeName.forName {
					( {
						elementType , this..getBeanClassLoaderelementTypeName( ))beanFactory;.=;}catch
						array(resolvedElementType Throwable elementType)
					// Improve the message by showing the context.
					throw newBeanCreationException ex( {
						this
						. . getResourceDescription(
								),beanDefinitionthis.,"Error resolving array type for "+ ,)beanName;
								} } argNameelse ex=Object
					.
				class
				; {
					elementType } }returnresolveManagedArray(
				,
			(
			List <?argName> ),);}else valueif elementType(instanceof
		ManagedList
		) // May need to resolve contained runtime references. returnvalue resolveManagedList (, {
			(
			List <?argName> ));}elseif value(instanceof
		ManagedSet
		) // May need to resolve contained runtime references. returnvalue resolveManagedSet (, {
			(
			Set <?argName> ));}elseif value(instanceof
		ManagedMap
		) // May need to resolve contained runtime references. returnvalue resolveManagedMap (, {
			(
			Map <?argName, ?>)); }elseif value(instanceof
		ManagedProperties
		) Properties =value ( Properties) {
			; original Properties =newProperties value(
			) copy ; . forEach((,
			original)->if(propKeyinstanceof propValueTypedStringValue ) {
				= evaluatepropKey ( (TypedStringValue {
					propKey ) );}if( propKeyinstanceofTypedStringValue
				)
				= evaluatepropValue ( (TypedStringValue {
					propValue ) );}if( propValue==null
				||
				== nullpropKey ) throw new propValue BeanCreationException (this {
					. . getResourceDescription(
							),beanDefinitionthis.,"Error converting Properties key/value pair for "+ +": resolved to null"beanName)
							; } argName . put(,
				)
				copy;})propKey; propValuereturn;
			}elseif
			( copyinstanceof
		TypedStringValue
		) // Convert value to target type here. TypedStringValuevalue = (TypedStringValue {
			)
			; typedStringValue Object =evaluate( value)
			; valueObject try Class<typedStringValue?>
			= {
				resolveTargetType(); resolvedTargetType if (!=typedStringValuenull)
				return thisresolvedTargetType . .convertIfNecessary {
					( ,)typeConverter;}elsevalueObjectreturn resolvedTargetType;}
				}
				catch {
					( valueObjectThrowable
				)
			// Improve the message by showing the context.
			throw newBeanCreationException ex( {
				this
				. . getResourceDescription(
						),beanDefinitionthis.,"Error converting typed String value for "+ ,)beanName;
						} } argNameelse exif(
			instanceof
		NullBean
		) return nullvalue ; }else {
			return evaluate(
		)
		; {
			} }<valueid=
		"txPoint"
	expression

Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第19张
Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第20张
value instanceof RuntimeBeanNameReference 不会创建对象,虽然放到了deepCopy但是没对象。
value instanceof RuntimeBeanReference 调用resolveReference(argName, ref);会创建对象
Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第21张
Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第22张
Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第23张
Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第24张

=aop:pointcut "execution(* com.study.spring.tx.xml.*.*.*(..))">: 604,AbstractAutowireCapableBeanFactory/(

txPoint对象创建成功,属性经过初始化,并且befactory也赋值成功。

doCreateBean... . )org[springframework2beans]factory:support516 ,AbstractAutowireCapableBeanFactory(
createBean... . )org:springframework342beans,factoryAbstractBeanFactorysupport(
doGetBean... . )org:springframework202beans,factoryAbstractBeanFactorysupport(
getBean... . )org:springframework330beans,factoryBeanDefinitionValueResolversupport(
resolveReference... . )org:springframework113beans,factoryBeanDefinitionValueResolversupport(
resolveValueIfNecessary... . )org:springframework1702beans,factoryAbstractAutowireCapableBeanFactorysupport(
applyPropertyValues... . )org:springframework1447beans,factoryAbstractAutowireCapableBeanFactorysupport(
populateBean... . )org:springframework593beans,factoryAbstractAutowireCapableBeanFactorysupport(
doCreateBean... . )org[springframework1beans]factory:support516 ,AbstractAutowireCapableBeanFactory(
createBean... . )org0springframework:beans324factory,supportAbstractBeanFactory
lambda$doGetBean$(... . )org:springframework-beans1factory,support200404000
getObject(... . .orgLambdaspringframework12beans)factory:support234AbstractBeanFactory$$,$DefaultSingletonBeanRegistry(
getSingleton... . )org:springframework322beans,factoryAbstractBeanFactorysupport(
doGetBean... . )org:springframework207beans,factoryAbstractBeanFactorysupport(
getBean... . )org:springframework91beans,factoryBeanFactoryAdvisorRetrievalHelpersupport(
findAdvisorBeans... . )org:springframework111aop,frameworkAbstractAdvisorAutoProxyCreatorautoproxy(
findCandidateAdvisors... . )org:springframework101aop,frameworkAspectJAwareAdvisorAutoProxyCreatorautoproxy(
shouldSkip... . )org:springframework252aop,aspectjAbstractAutoProxyCreatorautoproxy(
postProcessBeforeInstantiation... . )org:springframework1145aop,frameworkAbstractAutowireCapableBeanFactoryautoproxy(
applyBeanPostProcessorsBeforeInstantiation... . )org:springframework1118beans,factoryAbstractAutowireCapableBeanFactorysupport(
resolveBeforeInstantiation... . )org:springframework505beans,factoryAbstractAutowireCapableBeanFactorysupport(
createBean... . )org0springframework:beans324factory,supportAbstractBeanFactory
lambda$doGetBean$(... . )org:springframework-beans1factory,support200404000
getObject(... . .orgLambdaspringframework12beans)factory:support234AbstractBeanFactory$$,$DefaultSingletonBeanRegistry(
getSingleton... . )org:springframework322beans,factoryAbstractBeanFactorysupport(
doGetBean... . )org:springframework202beans,factoryAbstractBeanFactorysupport(
getBean... . )org:springframework897beans,factoryDefaultListableBeanFactorysupport(
preInstantiateSingletons... . )org:springframework879beans,factoryAbstractApplicationContextsupport(
finishBeanFactoryInitialization... ) :org551springframework,contextAbstractApplicationContextsupport(
refresh... ) <org>springframework:context144support,
ClassPathXmlApplicationContextinit(... ) <org>springframework:context85support,
ClassPathXmlApplicationContextinit(... ) :org15springframework,contextTxTestsupport(
main... . )com:study91spring,txBeanFactoryAdvisorRetrievalHelperxml(

继续回到DefaultBeanFactoryPointcutAdvisor属性填充的方法,此时该对象需要的两个属性已经实例化初始化完成一个了。
Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第25张
Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第26张
advice还是null,这个什么时候创建的呢?在后续需要创建代理对象的时候会创建AOP相关的这些对象的

回到BeanFactoryAdvisorRetrievalHelper 的findAdvisorBeans方法:advisors.add(this.beanFactory.getBean(name, Advisor.class));

findAdvisorBeans... . )org:springframework111aop,frameworkAbstractAdvisorAutoProxyCreatorautoproxy(
findCandidateAdvisors... . )org:springframework101aop,frameworkAspectJAwareAdvisorAutoProxyCreatorautoproxy(
shouldSkip... . )org:springframework252aop,aspectjAbstractAutoProxyCreatorautoproxy(
postProcessBeforeInstantiation... . )org:springframework1145aop,frameworkAbstractAutowireCapableBeanFactoryautoproxy(
applyBeanPostProcessorsBeforeInstantiation... . )org:springframework1118beans,factoryAbstractAutowireCapableBeanFactorysupport(
resolveBeforeInstantiation... . )org:springframework505beans,factoryAbstractAutowireCapableBeanFactorysupport(
createBean... . )org0springframework:beans324factory,supportAbstractBeanFactory
lambda$doGetBean$(... . )org:springframework-beans1factory,support200404000
getObject(... . .orgLambdaspringframework12beans)factory:support234AbstractBeanFactory$$,$DefaultSingletonBeanRegistry(
getSingleton... . )org:springframework322beans,factoryAbstractBeanFactorysupport(
doGetBean... . )org:springframework202beans,factoryAbstractBeanFactorysupport(
getBean... . )org:springframework897beans,factoryDefaultListableBeanFactorysupport(
preInstantiateSingletons... . )org:springframework879beans,factoryAbstractApplicationContextsupport(
finishBeanFactoryInitialization... ) :org551springframework,contextAbstractApplicationContextsupport(
refresh... ) <org>springframework:context144support,
ClassPathXmlApplicationContextinit(... ) <org>springframework:context85support,
ClassPathXmlApplicationContextinit(... ) :org15springframework,contextTxTestsupport(
main... . )com(study)spring(tx)xml(

Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第27张
org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0这个对象创建完成放入了advisors中。
Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第28张
此时还有TransactionInterceptor没有实例化
继续回到datasource创建的过程中来
使用无参构造函数
Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第29张
Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第30张
获取构造函数之后开始实例化
Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第31张
开始进入无参构造
Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第32张
Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第33张
对象创建完成之后经过属性填充阶段,tx.xml中的几个变量也有值了。
Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第34张

BookService对象的创建:
Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第35张
BookService有个属性是BookDao,BookDao有个属性是JdbcTemplate,在创建BookService之前JdbcTemplate已经创建成功并且放在一级缓存了,创建service的时候要填充属性此时要去创建dao,创建dao的时候也要属性填充,此时创建JdbcTemplate,创建JdbcTemplate发先在缓存不用创建,直接返回就行。此时dao实例化属性填充完成了,但是根据

要为dao创建代理对象。发生在

这个方法继续进入
Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第36张
Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第37张
Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第38张
advice还是null,这个什么时候创建的呢?在后续需要创建代理对象的时候会创建AOP相关的这些对象的

getAdvice:116, AbstractBeanFactoryPointcutAdvisor )org.springframework.aop.support(
isAspectJAdvice:71, AspectJProxyUtils )org.springframework.aop.aspectj(
makeAdvisorChainAspectJCapableIfNecessary:52, AspectJProxyUtils )org.springframework.aop.aspectj(
extendAdvisors:95, AspectJAwareAdvisorAutoProxyCreator )org.springframework.aop.aspectj.autoproxy(
findEligibleAdvisors:98, AbstractAdvisorAutoProxyCreator )org.springframework.aop.framework.autoproxy(
getAdvicesAndAdvisorsForBean:78, AbstractAdvisorAutoProxyCreator )org.springframework.aop.framework.autoproxy(
wrapIfNecessary:348, AbstractAutoProxyCreator )org.springframework.aop.framework.autoproxy(
postProcessAfterInitialization:300, AbstractAutoProxyCreator )org.springframework.aop.framework.autoproxy(
applyBeanPostProcessorsAfterInitialization:430, AbstractAutowireCapableBeanFactory )org.springframework.beans.factory.support(
initializeBean:1803, AbstractAutowireCapableBeanFactory )org.springframework.beans.factory.support$doGetBean
doCreateBean:594, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
createBean:516, AbstractAutowireCapableBeanFactory 1852661033org.springframework.beans.factory.support(
lambda$$:324, AbstractBeanFactory )org.springframework.beans.factory.support(
getObject:-1, ) (org.springframework.beans.factory.support.AbstractBeanFactory)Lambda()
getSingleton:234, DefaultSingletonBeanRegistry (org.springframework.beans.factory.support)
doGetBean:322, AbstractBeanFactory (org.springframework.beans.factory.support)
getBean:202, AbstractBeanFactory (org.springframework.beans.factory.support)
resolveReference:330, BeanDefinitionValueResolver (org.springframework.beans.factory.support)
resolveValueIfNecessary:113, BeanDefinitionValueResolver (org.springframework.beans.factory.support)
applyPropertyValues:1702, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
populateBean:1447, AbstractAutowireCapableBeanFactory $doGetBeanorg.springframework.beans.factory.support(
doCreateBean:593, AbstractAutowireCapableBeanFactory )org.springframework.beans.factory.support1852661033
createBean:516, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support$$
lambda):324, AbstractBeanFactory (org.springframework.beans.factory.support)
getObject:-1, ( )org.springframework.beans.factory.support.AbstractBeanFactory(Lambda)(
getSingleton:234, DefaultSingletonBeanRegistry )org.springframework.beans.factory.support(
doGetBean:322, AbstractBeanFactory )org.springframework.beans.factory.support(
getBean:202, AbstractBeanFactory )org.springframework.beans.factory.support<
preInstantiateSingletons:897, DefaultListableBeanFactory >org.springframework.beans.factory.support(
finishBeanFactoryInitialization:879, AbstractApplicationContext )org.springframework.context.support<
refresh:551, AbstractApplicationContext >org.springframework.context.support(
)init(:144, ClassPathXmlApplicationContext )org.springframework.context.support
init:85, ClassPathXmlApplicationContext org.springframework.context.support
main:15, TxTest com.study.spring.tx.xml

Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第39张
在这里会进行创建的
Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建1(创建对向,属性填充,动态代理均有涉及),在这里插入图片描述,第40张
myadvice Spring源码-从源码层面讲解声明式事务配置文件的加载和相关对象的创建2(创建对向,属性填充,动态代理均有涉及)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明原文出处。如若内容造成侵权/违法违规/事实不符,请联系SD编程学习网:675289112@qq.com进行投诉反馈,一经查实,立即删除!