spring源码的xml解析过程-4(IOC依赖注入)


查看 web.xml 文 件

   <!--
     web监听器说明:
     listener 监听器标签,
     web监听器可以监听客户端的请求和服务端的操作,同时它可以监听,
     包括 ServletContext、HttpSession、ServletRequest等

     监听器的启动顺序 :监听器>>过滤器>>Servlet
     
     加载spring容器,即父容器
     -->
    <listener>
        <listener-class>
        org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>

spring 加载入口(父容器)

org.springframework.web.context.ContextLoaderListener

   @Override
	public void contextInitialized(ServletContextEvent event) {
		initWebApplicationContext(event.getServletContext());
	}

spring mvc 加载入口(子容器)

 <!--
        servlet 标签
        Servlet 生命周期:
        1.在Servlet的生命周期中,仅执行一次init()方法
        2.service()方法 它是Servlet的核心,负责响应客户的请求.
          由service()方法,根据提交方式,选择性的执行doGet()方法和doPost()方法等
        3.destroy(): 仅执行一次,在服务器端停止且卸载Servlet时执行该方法

        相关类的说明:
        Servlet接口和GenericServlet是不特定于任何协议的,而HttpServlet是特定于HTTP协议的类,
        所以HttpServlet中实现了service()方法,并将请求ServletRequest、ServletResponse 强转为HttpRequest 和 HttpResponse
    -->
    <!-- spring 子容器入口,也就是 spring mvc 入口 DispatcherServlet 类 -->
    <!-- 
    不论是子容器还是父容器都会调用 AbstractApplicationContext 中的 refresh() 方法,
    所以 refresh() 方法 会被调用两次 
    -->
    <!-- springmvc的前端控制器 -->
    <servlet>
        <servlet-name>dn-spring-framework</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--
		contextConfigLocation不是必须的, 如果不配置contextConfigLocation,
		 springmvc的配置文件默认在:WEB-INF/servlet的name+"-servlet.xml"
		 -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:config/spring/springmvc.xml</param-value>
        </init-param>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>

        <!--<init-param>-->
        <!--<param-name>detectAllHandlerMappings</param-name>-->
        <!--<param-value>false</param-value>-->
        <!--</init-param>-->
        <!--
        1.如果web.xml中配置了<load-on-startup>属性,在Tomcat初始化时按其值从小到大的顺序加载所有servlet的init方法
        2.如果没有配置<load-on-startup>属性,容器初始化时不加载。在请求匹配的url时进行加载,
          并且只加载最后一个servlet的init方法。其他的servlet不加载
        -->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <!-- 拦截所有资源请求 -->
    <servlet-mapping>
        <servlet-name>dn-spring-framework</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>  

org.springframework.context.support.AbstractApplicationContext#refresh 的方法会被 spring 容器 、spring mvc 容器加载两次

org.springframework.context.support.AbstractApplicationContext#refresh

// 注册容器的监听器
registerListeners();

org.springframework.context.support.AbstractApplicationContext#registerListeners

// 监听器放入到集合中
for (ApplicationListener<?> listener : getApplicationListeners())
{			getApplicationEventMulticaster().addApplicationListener(listener);
}

// 获取 ApplicationListener 类的所有实现类
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) 
{			getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}

if (earlyEventsToProcess != null) {
// 循环所有监听器,并执行
  for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
				getApplicationEventMulticaster().multicastEvent(earlyEvent);
			}
		}

org.springframework.context.event.SimpleApplicationEventMulticaster#multicastEvent(org.springframework.context.ApplicationEvent)

multicastEvent(event, resolveDefaultEventType(event));

org.springframework.context.event.SimpleApplicationEventMulticaster#multicastEvent(org.springframework.context.ApplicationEvent, org.springframework.core.ResolvableType)

@Override
	public void multicastEvent(final ApplicationEvent event, ResolvableType eventType) {
		ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));

 // 为每个监听器启一个线程		
 for (final ApplicationListener<?> listener : getApplicationListeners(event, type)) {
			Executor executor = getTaskExecutor();
			if (executor != null) {
				executor.execute(new Runnable() {
					@Override
					public void run() {
						invokeListener(listener, event);
					}
				});
			}
			else {
				invokeListener(listener, event);
			}
		}
	}

实现了 ApplicationListener 接口的所有实现类都会注册到 ListenerRetriever 类中的 applicationListeners 、applicationListenerBeans 属性中,往 spring 容器中注册发布 ApplicationEvent, 监听器方法 onApplicationEvent 将会被触发 ,这其实就是观察者模式

主题
subject -> event
观察者
obverse-> listener

    /**
     * 监听器测试
     */
    @Test
    public void test5() {
        MyEvent myEvent = new MyEvent("自定义监听器");
        // 发布事件,给所有的监听者,通过广播的方式
        context.publishEvent(myEvent);

        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

查看 publishEvent 方法
org.springframework.context.support.AbstractApplicationContext#publishEvent(org.springframework.context.ApplicationEvent)

publishEvent(event, null);

org.springframework.context.support.AbstractApplicationContext#publishEvent(java.lang.Object, org.springframework.core.ResolvableType)

if (event instanceof ApplicationEvent) {
	applicationEvent = (ApplicationEvent) event;
}

//循环调用所有的监听器
getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);

org.springframework.context.event.SimpleApplicationEventMulticaster#multicastEvent(org.springframework.context.ApplicationEvent, org.springframework.core.ResolvableType)

循环所有监听器,并为每个监听器创建个线程去调用监听器

		for (final ApplicationListener<?> listener : getApplicationListeners(event, type)) {
			Executor executor = getTaskExecutor();
			if (executor != null) {
				executor.execute(new Runnable() {
					@Override
					public void run() {
						invokeListener(listener, event);
					}
				});
			}
			else {
				invokeListener(listener, event);
			}
		}


org.springframework.context.event.SimpleApplicationEventMulticaster#invokeListener

doInvokeListener(listener, event);

org.springframework.context.event.SimpleApplicationEventMulticaster#doInvokeListener

调用监听器中的 onApplicationEvent 方法

listener.onApplicationEvent(event);

返回到
org.springframework.context.support.AbstractApplicationContext#refresh

// BeanDefinition的实例化以及 IOC 的依赖注入的过程
finishBeanFactoryInitialization(beanFactory);

org.springframework.context.support.AbstractApplicationContext#finishBeanFactoryInitialization

// conversionService 标签,类型装换器标签服务
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
				beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
			beanFactory.setConversionService(
					beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
		}

// ${} 占位符的解析类 PropertyPlaceholderConfigurer#resolveStringValue
	if (!beanFactory.hasEmbeddedValueResolver()) {
	       //
			beanFactory.addEmbeddedValueResolver(new StringValueResolver() {
			   // 注册默认的字符串解析策略,例如解析 ${} 占位符
				@Override
				public String resolveStringValue(String strVal) {
					return getEnvironment().resolvePlaceholders(strVal);
				}
			});
		}

//重点
beanFactory.preInstantiateSingletons();

org.springframework.beans.factory.support.DefaultListableBeanFactory#preInstantiateSingletons

List<String> beanNames = new ArrayList<String>(this.beanDefinitionNames);

// 在这里可以查看 spring 容器中的 父容器和子容器spring mvc 中的bean名称
for (String beanName : beanNames) {//重点
getBean(beanName);

org.springframework.beans.factory.support.AbstractBeanFactory#getBean(java.lang.String)

return doGetBean(name, null, null, false);

org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean

final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
//BeanDefinition依赖的bean
String[] dependsOn = mbd.getDependsOn();
// 依赖处理
.....

		// Create bean instance.
		        // BeanDefinition是单例
				if (mbd.isSingleton()) {
					sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
						@Override
						public Object getObject() throws BeansException {
							try {
							    // 重点
								return createBean(beanName, mbd, args);
							}
							catch (BeansException ex) {
								destroySingleton(beanName);
								throw ex;
							}
						}
					});
					bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
				}
	//BeanDefinition是多例
	else if (mbd.isPrototype()) {
					// It's a prototype -> create a new instance.
					Object prototypeInstance = null;
					try {
						beforePrototypeCreation(beanName);
						prototypeInstance = createBean(beanName, mbd, args);
					}
					finally {
						afterPrototypeCreation(beanName);
					}
					bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
				}				
else {
      // 其他bean 的作用域
		String scopeName = mbd.getScope();
}

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean(java.lang.String, org.springframework.beans.factory.support.RootBeanDefinition, java.lang.Object[])

// 在这里可以生成代理类对象
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#resolveBeforeInstantiation


bean = 
applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);

bean = 
applyBeanPostProcessorsAfterInitialization(bean, beanName);

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsBeforeInstantiation

// 循环 BeanPostProcessor 的所有子类
	for (BeanPostProcessor bp : getBeanPostProcessors()) {
			if (bp instanceof InstantiationAwareBeanPostProcessor) {
				InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
				// 重点
				Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
				if (result != null) {
					return result;
				}
			}
		}

InstantiationAwareBeanPostProcessor(扩展类)

  1. postProcessBeforeInstantiation
  2. postProcessAfterInstantiation

BeanPostProcessor(扩展类)

  1. postProcessBeforeInitialization
  2. postProcessAfterInitialization

InstantiationAwareBeanPostProcessor 的子类

  1. CommonAnnotationBeanPostProcessor,解析 @PostConstruct、@PreDestroy (由父类完成解析)和 bean中的 @Resource注解依赖注入的支持
    参考:https://blog.csdn.net/shenchaohao12321/article/details/81235571
  2. AOP 标签解析类 org.springframework.aop.config.AopNamespaceHandler
  3. AutowiredAnnotationBeanPostProcessor 类 @Autowired 、@Value 注解依赖注入的支持

CommonAnnotationBeanPostProcessor 和 AutowiredAnnotationBeanPostProcessor 类是在包扫描时(ComponentScanBeanDefinitionParser)注册到spring中的

aop 标签解析注册

// 注解 aop 解析类
registerBeanDefinitionParser("aspectj-autoproxy", new AspectJAutoProxyBeanDefinitionParser());

org.springframework.aop.config.AspectJAutoProxyBeanDefinitionParser#parse

AopNamespaceUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(parserContext, element);

org.springframework.aop.config.AopNamespaceUtils#registerAspectJAnnotationAutoProxyCreatorIfNecessary

public static BeanDefinition registerAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry, Object source) {
		return registerOrEscalateApcAsRequired(InfrastructureAdvisorAutoProxyCreator.class, registry, source);
	}

InfrastructureAdvisorAutoProxyCreator 类继承了 AbstractAdvisorAutoProxyCreator 类,AbstractAdvisorAutoProxyCreator 又继承了 AbstractAutoProxyCreator 类,即AOP的入口类,在解析AOP 的标签时,就会将 AOP 的入口类注册到spring 中

返回到
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean(java.lang.String, org.springframework.beans.factory.support.RootBeanDefinition, java.lang.Object[])

Object beanInstance = doCreateBean(beanName, mbdToUse, args);

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean

bean实例化、IOC依赖注入过程

//通过反射的方式创建 Bean 的实例,即通过构造器创建bean
instanceWrapper = createBeanInstance(beanName, mbd, args);

// IOC 依赖注入过程, @Autowired、 @Resource 的依赖注入
populateBean(beanName, mbd, instanceWrapper);

// 1.在bean实例化和 ioc 依赖注入后,对bean的前置初始化工作
// 2. InitializingBean#afterPropertiesSet 方法调用
// 3. bean 上的 init-method 属性配置的方法调用 
exposedObject = initializeBean(beanName, exposedObject, mbd);

// 完成 bean 的缓存注册工作,把 bean 注册到 map 中,即bbean缓存起来
registerDisposableBeanIfNecessary(beanName, bean, mbd);

依赖注入方式

  1. xml标签 ref 引用beanId
  2. 注解注入bean

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean

// bean 中的属性值列表
PropertyValues pvs = mbd.getPropertyValues();

// 当 InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation 
// 返回false 时,就不会依赖注入了
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
						continueWithPropertyPopulation = false;
						break;
					}
if (!continueWithPropertyPopulation) {
			return;
		}					


for (BeanPostProcessor bp : getBeanPostProcessors()) {
		if (bp instanceof InstantiationAwareBeanPostProcessor) {
			InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
	// 调用 InstantiationAwareBeanPostProcessor#postProcessPropertyValues
	// 方法,这里其实就是注解依赖注入的支持过程					
		    pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
						if (pvs == null) {
							return;
						}
					}
				}
// 查看该方法
applyPropertyValues(beanName, mbd, bw, pvs);	

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyPropertyValues

		if (pvs instanceof MutablePropertyValues) {
			mpvs = (MutablePropertyValues) pvs;
			if (mpvs.isConverted()) {
				// Shortcut: use the pre-converted values as-is.
				try {
					bw.setPropertyValues(mpvs);
					return;
				}
				catch (BeansException ex) {
					throw new BeanCreationException(
							mbd.getResourceDescription(), beanName, "Error setting property values", ex);
				}
			}
			// bean中的属性list
			original = mpvs.getPropertyValueList();
		}
// 属性类型转换器,比如list、map 等 
TypeConverter converter = getCustomTypeConverter();		

	for (PropertyValue pv : original) {
	//属性名
	String propertyName = pv.getName();
	//属性值
	Object originalValue = pv.getValue();
	//属性值解析器,例如属性值可能是ref、map、list、array 、string 时,怎么做处理
	Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
	}
// BeanWrapper#setPropertyValues : IOC 依赖注入的入口方法
bw.setPropertyValues(new MutablePropertyValues(deepCopy));
  1. PropertyTokenHolder 中的 keys 当依赖注入的类型是 array、list、map 类型时数据 keys 数组是不为空,里面的元素就就是 array、list、的 index, map 时是key
  2. PropertyHandler 对象封装了 PropertyDescriptor ,使用 jdk 反射的内省机制,根据 field 名称来获取 read、write 方法(即对应属性的 setXX、getXX方法)来读写属性的值

org.springframework.beans.AbstractPropertyAccessor#setPropertyValues(org.springframework.beans.PropertyValues)

setPropertyValues(pvs, false, false);

org.springframework.beans.AbstractPropertyAccessor#setPropertyValues(org.springframework.beans.PropertyValues, boolean, boolean)

//循环 bean 配置的多个属性,也就是bean 中的所有属性,进行注入处理
for (PropertyValue pv : propertyValues) {
	setPropertyValue(pv);
}

PropertyValue 就是: 一个标签的封装对象,PropertyValue 类中 value 就是对应的值,值可是是 List 、Map、String 等

value: 就是这个list对象,其中值就是 a,b,c

	<property name="mylist">
         <list>
                <value>a</value>
                <value>b</value>
                <value>c</value>
         </list>
	</property>

org.springframework.beans.AbstractNestablePropertyAccessor#setPropertyValue(org.springframework.beans.PropertyValue)

nestedPa.setPropertyValue(tokens, pv);

org.springframework.beans.AbstractNestablePropertyAccessor#setPropertyValue(org.springframework.beans.AbstractNestablePropertyAccessor.PropertyTokenHolder, org.springframework.beans.PropertyValue)

       if (tokens.keys != null) {
        //  <property name="list[0]" value="1"></property>
        
           //查看该方法
			processKeyedProperty(tokens, pv);
		}
		else {
		  // 这种配置,进入该方法(大部分走该方法)
		  // <list>
         //       <value>a</value>
        //        <value>b</value>
        //        <value>c</value>
         //   </list>
			processLocalProperty(tokens, pv);
		}

  1. PropertyTokenHolder tokens.keys 当array、list、map类型数据时keys数组不为空,里面的元素就是array、list的index,map的key
  2. PropertyHandler对象封装了PropertyDescriptor,用jdk反射中的内省机制来获取read、write方法,来读写属性的值

第一种List 赋值的方式
org.springframework.beans.AbstractNestablePropertyAccessor#processKeyedProperty

// 获取属性值
Object propValue = getPropertyHoldingValue(tokens);
// keys数组不为空,里面的元素就是array、list的index,map的key
String lastKey = tokens.keys[tokens.keys.length - 1];

if (propValue.getClass().isArray()) {

}else if (propValue instanceof List) {
//根据属性名称获取属性的类型对象
PropertyHandler ph = getPropertyHandler(tokens.actualName);
// 对属性值进行类型转换(xml中配置的一般都是字符串,这里将字符串转换为bean中属性的相应类型)
Object convertedValue = 
convertIfNecessary(tokens.canonicalName, oldValue, pv.getValue(),
					requiredType, ph.nested(tokens.keys.length));
//设置对应索引上的值
list.set(index, convertedValue);
}
else if (propValue instanceof Map) {
}

配置 List 方式二
org.springframework.beans.AbstractNestablePropertyAccessor#processLocalProperty

// 根据属性名称获取属性的类型对象
PropertyHandler ph = getLocalPropertyHandler(tokens.actualName);
// pv 就是属性和值的的封装对象
// originalValue 可能是 List、Map 对象的值 
Object originalValue = pv.getValue();

// ph 就是属性的 set 方法
//将属性值赋值到bean的属性上去
ph.setValue(this.wrappedObject, valueToApply);

org.springframework.beans.BeanWrapperImpl#getLocalPropertyHandler

// 根据 class中的 filed 名字 获取 filed 的读写方法(set、get),
// jdk中的内省机制对象
PropertyDescriptor pd =
getCachedIntrospectionResults().getPropertyDescriptor(propertyName);

if (pd != null) {
	//存放jdk内省机制对象
	return new BeanPropertyHandler(pd);
}

返回到
org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean

		// Create bean instance.
				if (mbd.isSingleton()) {
					sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
					   //回调方法,这种方式就可以不用实现类了,即匿名内部类
						@Override
						public Object getObject() throws BeansException {
							try {
							   // 查询该方法
								return createBean(beanName, mbd, args);
							}
							catch (BeansException ex) {
								destroySingleton(beanName);
								throw ex;
							}
						}
					});
					bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
				}

org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#getSingleton(java.lang.String, org.springframework.beans.factory.ObjectFactory<?>)

try {
	// 调用回调方法
	singletonObject = singletonFactory.getObject();
	newSingleton = true;
				}

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean(java.lang.String, org.springframework.beans.factory.support.RootBeanDefinition, java.lang.Object[])

Object beanInstance = doCreateBean(beanName, mbdToUse, args);

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean

populateBean(beanName, mbd, instanceWrapper);

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean

对注解的支持,依赖注入对象


for (BeanPostProcessor bp : getBeanPostProcessors()) {
	if (bp instanceof InstantiationAwareBeanPostProcessor) {
		InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
		pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
			if (pvs == null) {
					return;
					}
				}
}
  1. CommonAnnotationBeanPostProcessor#postProcessPropertyValues
  2. AutowiredAnnotationBeanPostProcessor#postProcessPropertyValues

org.springframework.context.annotation.CommonAnnotationBeanPostProcessor#postProcessPropertyValues

InjectionMetadata metadata = 
findResourceMetadata(beanName, bean.getClass(), pvs);

//属性或方法上注入对象
metadata.inject(bean, beanName, pvs);

org.springframework.context.annotation.CommonAnnotationBeanPostProcessor#findResourceMetadata

// 扫描类上的所有注解
metadata = buildResourceMetadata(clazz);

org.springframework.context.annotation.CommonAnnotationBeanPostProcessor#buildResourceMetadata

// 属性上查找注解
ReflectionUtils.doWithLocalFields
// 方法上查找注解
ReflectionUtils.doWithLocalMethods

InjectionMetadata
private volatile Set<InjectedElement> checkedElements;
InjectedElement 需要依赖注入的属性或者方法
protected final Member member; 属性或方法的封装对象

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean

beans实例化后初始化方法的执行

// 初始化方法的执行
exposedObject = initializeBean(beanName, exposedObject, mbd);

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean(java.lang.String, java.lang.Object, org.springframework.beans.factory.support.RootBeanDefinition)

// 调用 BeanPostProcessor#postProcessBeforeInitialization
wrappedBean = 
applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);

// 调用bean的初始化方法 (在bean实例化以后调用)
invokeInitMethods(beanName, wrappedBean, mbd);

if (mbd == null || !mbd.isSynthetic()) {
// AOP 代理类入口
// 1.被代理类只有实例化后,才能被代理
// 2.这里是产生AOP代理类的入口
			wrappedBean = 
		   applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
  1. afterPropertiesSet bean初始化方法
  2. init-method 指定的bean初始化方法

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsAfterInitialization

        Object result = existingBean;
		for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
		   // 查看该方法
			result = beanProcessor.postProcessAfterInitialization(result, beanName);
			if (result == null) {
				return result;
			}
		}
		return result;

org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#postProcessAfterInitialization

if (!this.earlyProxyReferences.contains(cacheKey)) {
		return wrapIfNecessary(bean, beanName, cacheKey);
	}

org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#wrapIfNecessary

// 获取类上的 advisor,即该 bean 的增强类,查看该方法
Object[] specificInterceptors = 
getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
		if (specificInterceptors != DO_NOT_PROXY) {
			this.advisedBeans.put(cacheKey, Boolean.TRUE);
			// 产生代理类
			Object proxy = createProxy(
					bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
			this.proxyTypes.put(cacheKey, proxy.getClass());
			return proxy;
		}

wrapIfNecessary 方法入参 Object bean 被代理类的实现类,例如 service的实现类
AbstractAutoProxyCreator 类是个抽象类,所以是子类调到 AbstractAutoProxyCreator#wrapIfNecessary 方法的,那子类是在哪初始化的呢,是在解析aop标签时,注册进来的,即 org.springframework.aop.config.ConfigBeanDefinitionParser#parse 方法中的 configureAutoProxyCreator(parserContext, element);,在 org.springframework.aop.config.AopConfigUtils#registerAspectJAutoProxyCreatorIfNecessary(org.springframework.beans.factory.support.BeanDefinitionRegistry, java.lang.Object) 方法中进行了注册 AspectJAwareAdvisorAutoProxyCreator 类,而这个类的父类就是 AbstractAutoProxyCreator类。

返回到
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean

// 将实例化的bean 进行注册,即缓存起来
registerDisposableBeanIfNecessary(beanName, bean, mbd);

总结

spring容器初始化入口
监听器
spring aop 入口
IOC 依赖注入过程
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值