测试用例1
测试用例:一个userController类,类里有个属性userService,被@autowired注解
@Component
public class UserController {
@Autowired
private UserService userService;
public void testController(){
}
}
测试用例2
测试用例:启动引导类,新建spring容器对象AnnotationConfigApplicationContext
@Configuration
@ComponentScan
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class DemoApplication {
public static void main( String[] args ) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(DemoApplication.class);
UserService userService = (UserService) ctx.getBean("userServiceImpl");
UserInfo userInfo = (UserInfo) ctx.getBean("user_zhangsan");
userService.save(userInfo);
}
}
前置断点:创建userController对象
代码块1:main
@Autowired属性注入用于在userController类中注入userService属性,所以首先需要创建userController对象
参数:args=[]
package com.helloworld;
public class DemoApplication {
public static void main( String[] args ) {
"*******"AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(DemoApplication.class);
"(1) 新建spring容器对象,AnnotationConfigApplicationContext,参数是启动类的类名"
"参数:annotatedClasses=class com.helloworld.DemoApplication,"
UserService userService = (UserService) ctx.getBean("userServiceImpl");
UserInfo userInfo = (UserInfo) ctx.getBean("user_zhangsan");
userService.save(userInfo);
}
}
代码块2:AnnotationConfigApplicationContext()
AnnotationConfigApplicationContext构造器,负责注册引导类或主配置类bean定义,并刷新容器
参数:annotatedClasses=class com.helloworld.DemoApplication,
package org.springframework.context.annotation;
public class AnnotationConfigApplicationContext extends GenericApplicationContext implements AnnotationConfigRegistry{
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
this();
register(annotatedClasses);
"*******"refresh();
"(2) 核心方法,刷新spring容器"
}
}
代码块3:refresh
搜集工程中的所有bean定义,并依次创建实例;
package org.springframework.context.support;
public class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext{
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
......
onRefresh();
registerListeners();
"***************"finishBeanFactoryInitialization(beanFactory);
"(3) bean定义搜集完毕,开始创建实例"
"参数:beanFactory=org.springframework.beans.factory.support.DefaultListableBeanFactory@7960847b: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,demoApplication,testAspect,userController,myBeanPostProcessor,myBeanFactoryPostProcessor,userServiceImpl,user_zhangsan,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy"
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
......
resetCommonCaches();
}
}
}
}
代码块4:finishBeanFactoryInitialization
实例化所有单例bean
参数:beanFactory=org.springframework.beans.factory.support.DefaultListableBeanFactory@7960847b: defining beans [org.springfra…
package org.springframework.context.support;
public class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext{
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
......
beanFactory.setTempClassLoader(null);
beanFactory.freezeConfiguration();
"*******"beanFactory.preInstantiateSingletons();
"(4) 实例化所有单例bean"
}
}
代码块5:preInstantiateSingletons
遍历所有的bean设计图,判断是否是factoryBean,还是普通bean
package org.springframework.beans.factory.support;
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{
@Override
public void preInstantiateSingletons() throws BeansException {
if (logger.isTraceEnabled()) {
logger.trace("Pre-instantiating singletons in " + this);
......
if (isEagerInit) {
getBean(beanName);
}
}
}
else {
"*******************"getBean(beanName);
"(5) userController是普通bean,不是factoryBean,继续执行getBean"
"参数:name=userController"
}
}
}
for (String beanName : beanNames) {
Object singletonInstance = getSingleton(beanName);
if (singletonInstance instanceof SmartInitializingSingleton) {
......
}
}
}
}
}
代码块6:getBean
do开头的方法,开始真正创建bean
参数:name=userController
package org.springframework.beans.factory.support;
public class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory{
@Override
public Object getBean(String name) throws BeansException {
"*******"return doGetBean(name, null, null, false);
"(6) do开头的方法,开始真正创建bean"
"参数:name=userController"
"参数:typeCheckOnly=false"
}
}
代码块7:doGetBean
lamda表达式的函数式编程写法,实际执行创建bean方法
参数:name=userController
参数:typeCheckOnly=false
package org.springframework.beans.factory.support;
public class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory{
@SuppressWarnings("unchecked")
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
......
}
}
}
if (mbd.isSingleton()) {
"*******************"sharedInstance = getSingleton(beanName, () -> {
"(7) lamda表达式的函数式编程写法,实际执行创建bean方法"
"参数:beanName=userController"
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
destroySingleton(beanName);
......
}
}
return (T) bean;
}
}
代码块8:getSingleton
函数式编程写法,实际执行创建bean方法
参数:beanName=userController
package org.springframework.beans.factory.support;
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry{
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
synchronized (this.singletonObjects) {
Object singletonObject = this.singletonObjects.get(beanName);
......
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
try {
"*******************"singletonObject = singletonFactory.getObject();
"(8) 函数式编程写法,实际执行创建bean方法,参考@FunctionalInterface注解"
"参数:beanName=userController"
"参数:mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]"
newSingleton = true;
}
catch (IllegalStateException ex) {
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
throw ex;
......
}
return singletonObject;
}
}
}
代码块9:createBean
主要执行对象创建前的处理器及创建对象实例
参数:beanName=userController
参数:mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowi…
package org.springframework.beans.factory.support;
public class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory{
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
......
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
try {
"***********"Object beanInstance = doCreateBean(beanName, mbdToUse, args);
"(9) lamda表达式真正执行的方法,创建对象实例"
"参数:beanName=userController"
"参数:mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]"
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
......
throw new BeanCreationException(
mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
}
}
}
代码块10:doCreateBean
1.创建对象。2.执行对象创建后的处理器。3.填充对象属性
参数:beanName=userController
参数:mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowi…
package org.springframework.beans.factory.support;
public class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory{
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
"***********"instanceWrapper = createBeanInstance(beanName, mbd, args);
"(10) 找到userController的构造器,使用构造器反射创建实例,至此,准备工作完成"
}
final Object bean = instanceWrapper.getWrappedInstance();
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
......
}
return exposedObject;
}
}
总结:
前置断点:创建userController对象
- DemoApplication.main()————AnnotationConfigApplicationContext ctx = new Annot…
- AnnotationConfigApplicationContext.AnnotationConfigApplicationContext()————refresh();
- AbstractApplicationContext.refresh()————finishBeanFactoryInitialization(beanFactory);
- AbstractApplicationContext.finishBeanFactoryInitialization()————beanFactory.preInstantiateSingletons();
- DefaultListableBeanFactory.preInstantiateSingletons()————getBean(beanName);
- AbstractBeanFactory.getBean()————return doGetBean(name, null, null, false);
- AbstractBeanFactory.doGetBean()————sharedInstance = getSingleton(beanName, () -> {
- DefaultSingletonBeanRegistry.getSingleton()————singletonObject = singletonFactory.getObject();
- AbstractAutowireCapableBeanFactory.createBean()————Object beanInstance = doCreateBean(beanName, mbdTo…
- AbstractAutowireCapableBeanFactory.doCreateBean()————instanceWrapper = createBeanInstance(beanName, mbd…
断点一:找到UserController类中的属性userService,封装成元数据
代码块11:doCreateBean
回到doCreateBean,执行对象创建后的处理器。
参数:beanName=userController
参数:mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowi…
package org.springframework.beans.factory.support;
public class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory{
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {
......
"***********"instanceWrapper = createBeanInstance(beanName, mbd, args);
"(10)"
}
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
"*******************"applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
"(11) 回到doCreateBean,userController对象创建完毕后,执行对象创建后的处理器"
"参数:mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]"
"参数:beanType=class com.helloworld.controller.UserController"
"参数:beanName=userController"
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}
......
}
return exposedObject;
}
}
代码块12:applyMergedBeanDefinitionPostProcessors
依次调用bean后置处理器
参数:mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowi…
参数:beanType=class com.helloworld.controller.UserController
参数:beanName=userController
package org.springframework.beans.factory.support;
public class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory{
protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof MergedBeanDefinitionPostProcessor) {
MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
"***************"bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
"(12) 依次调用bean后置处理器"
"参数:beanDefinition=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]"
"参数:beanType=class com.helloworld.controller.UserController"
"参数:beanName=userController"
}
}
}
}
代码块13:postProcessMergedBeanDefinition
@Autowired注解对应类的关键方法,查找userController类的自动装配属性userService,将其封装成元数据
参数:beanDefinition=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=fa…
参数:beanType=class com.helloworld.controller.UserController
参数:beanName=userController
package org.springframework.beans.factory.annotation;
public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor{
@Override
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
"*******"InjectionMetadata metadata = findAutowiringMetadata(beanName, beanType, null);
"(13) 查找userController类的自动装配属性userService,封装成元数据"
"参数:beanName=userController"
"参数:clazz=class com.helloworld.controller.UserController"
metadata.checkConfigMembers(beanDefinition);
}
}
代码块14:findAutowiringMetadata
根据userController类的userService属性,构建userController类的autowired自动装配元数据
参数:beanName=userController
参数:clazz=class com.helloworld.controller.UserController
package org.springframework.beans.factory.annotation;
public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor{
private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) {
String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
......
synchronized (this.injectionMetadataCache) {
metadata = this.injectionMetadataCache.get(cacheKey);
if (InjectionMetadata.needsRefresh(metadata, clazz)) {
if (metadata != null) {
metadata.clear(pvs);
}
"*******************"metadata = buildAutowiringMetadata(clazz);
"(14) 根据userController类的userService属性,构建userController类的autowired自动装配元数据"
"参数:clazz=class com.helloworld.controller.UserController"
this.injectionMetadataCache.put(cacheKey, metadata);
}
}
}
return metadata;
}
}
代码块15:buildAutowiringMetadata
函数式编程,实际上执行的是findAutowiredAnnotation
参数:clazz=class com.helloworld.controller.UserController
package org.springframework.beans.factory.annotation;
public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor{
private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {
List<InjectionMetadata.InjectedElement> elements = new ArrayList<>();
Class<?> targetClass = clazz;
do {
final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>();
"***********"ReflectionUtils.doWithLocalFields(targetClass, field -> {
"(15) 函数式编程,实际上执行的是findAutowiredAnnotation,执行这个方法后,第22行代码对执行结果进行封装;最后一行创建依赖注入元数据并返回"
"参数:ao=private com.helloworld.service.UserService com.helloworld.controller.UserController.userService"
AnnotationAttributes ann = findAutowiredAnnotation(field);
if (ann != null) {
if (Modifier.isStatic(field.getModifiers())) {
if (logger.isInfoEnabled()) {
logger.info("Autowired annotation is not supported on static fields: " + field);
}
return;
}
......
while (targetClass != null && targetClass != Object.class);
return new InjectionMetadata(clazz, elements);
}
}
代码块16:findAutowiredAnnotation
获取autowire自动装配属性,即userService
参数:ao=private com.helloworld.service.UserService com.helloworld.controller.UserController.userService
package org.springframework.beans.factory.annotation;
public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor{
@Nullable
private AnnotationAttributes findAutowiredAnnotation(AccessibleObject ao) {
if (ao.getAnnotations().length > 0) {
for (Class<? extends Annotation> type : this.autowiredAnnotationTypes) {
"***************"AnnotationAttributes attributes = AnnotatedElementUtils.getMergedAnnotationAttributes(ao, type);
"(16) 获取autowire自动装配属性,即userService"
"参数:element=private com.helloworld.service.UserService com.helloworld.controller.UserController.userService"
"参数:annotationType=interface org.springframework.beans.factory.annotation.Autowired"
if (attributes != null) {
return attributes;
}
}
}
return null;
}
}
代码块17:getMergedAnnotationAttributes
找到默认属性required=true
参数:element=private com.helloworld.service.UserService com.helloworld.controller.UserController.userService
参数:annotationType=interface org.springframework.beans.factory.annotation.Autowired
package org.springframework.core.annotation;
public class AnnotatedElementUtils {
@Nullable
public static AnnotationAttributes getMergedAnnotationAttributes(
AnnotatedElement element, Class<? extends Annotation> annotationType) {
"*******"AnnotationAttributes attributes = searchWithGetSemantics(element, annotationType, null,
"(17) 找到@Autorwired默认属性required=true,至此找到被@Autowired注解的属性userService及注解的默认属性required=true,回到findAutowiringMetadata方法,放入缓存injectionMetadataCache"
new MergedAnnotationAttributesProcessor());
AnnotationUtils.postProcessAnnotationAttributes(element, attributes, false, false);
return attributes;
}
}
总结:
断点一:找到UserController类中的属性userService,封装成元数据
- DemoApplication.main()————AnnotationConfigApplicationContext ctx = new Annot…
- AnnotationConfigApplicationContext.AnnotationConfigApplicationContext()————refresh();
- AbstractApplicationContext.refresh()————finishBeanFactoryInitialization(beanFactory);
- AbstractApplicationContext.finishBeanFactoryInitialization()————beanFactory.preInstantiateSingletons();
- DefaultListableBeanFactory.preInstantiateSingletons()————getBean(beanName);
- AbstractBeanFactory.getBean()————return doGetBean(name, null, null, false);
- AbstractBeanFactory.doGetBean()————sharedInstance = getSingleton(beanName, () -> {
- DefaultSingletonBeanRegistry.getSingleton()————singletonObject = singletonFactory.getObject();
- AbstractAutowireCapableBeanFactory.createBean()————Object beanInstance = doCreateBean(beanName, mbdTo…
- AbstractAutowireCapableBeanFactory.doCreateBean()————applyMergedBeanDefinitionPostProcessors(mbd, beanT…
- AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors()————bdp.postProcessMergedBeanDefinition(mbd, beanType,…
- AutowiredAnnotationBeanPostProcessor.postProcessMergedBeanDefinition()————InjectionMetadata metadata = findAutowiringMetadat…
- AutowiredAnnotationBeanPostProcessor.findAutowiringMetadata()————metadata = buildAutowiringMetadata(clazz);
- AutowiredAnnotationBeanPostProcessor.buildAutowiringMetadata()————ReflectionUtils.doWithLocalFields(targetClass, fie…
- AutowiredAnnotationBeanPostProcessor.findAutowiredAnnotation()————AnnotationAttributes attributes = AnnotatedElement…
- AnnotatedElementUtils.getMergedAnnotationAttributes()————AnnotationAttributes attributes = searchWithGetSem…
断点二:填充userController属性,准备依赖注入
代码块18:findAutowiringMetadata
将解析的元数据放到injectionMetadataCache缓存,以备复用
参数:beanName=userController
参数:clazz=class com.helloworld.controller.UserController
package org.springframework.beans.factory.annotation;
public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor{
private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) {
String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
......
metadata = this.injectionMetadataCache.get(cacheKey);
if (InjectionMetadata.needsRefresh(metadata, clazz)) {
if (metadata != null) {
metadata.clear(pvs);
}
"*******************"metadata = buildAutowiringMetadata(clazz);
"(14)"
"*******************"this.injectionMetadataCache.put(cacheKey, metadata);
"(18) 将解析的元数据放到injectionMetadataCache缓存,以备复用"
}
}
}
return metadata;
}
}
总结:
断点二:填充userController属性,准备依赖注入
- DemoApplication.main()————AnnotationConfigApplicationContext ctx = new Annot…
- AnnotationConfigApplicationContext.AnnotationConfigApplicationContext()————refresh();
- AbstractApplicationContext.refresh()————finishBeanFactoryInitialization(beanFactory);
- AbstractApplicationContext.finishBeanFactoryInitialization()————beanFactory.preInstantiateSingletons();
- DefaultListableBeanFactory.preInstantiateSingletons()————getBean(beanName);
- AbstractBeanFactory.getBean()————return doGetBean(name, null, null, false);
- AbstractBeanFactory.doGetBean()————sharedInstance = getSingleton(beanName, () -> {
- DefaultSingletonBeanRegistry.getSingleton()————singletonObject = singletonFactory.getObject();
- AbstractAutowireCapableBeanFactory.createBean()————Object beanInstance = doCreateBean(beanName, mbdTo…
- AbstractAutowireCapableBeanFactory.doCreateBean()————applyMergedBeanDefinitionPostProcessors(mbd, beanT…
- AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors()————bdp.postProcessMergedBeanDefinition(mbd, beanType,…
- AutowiredAnnotationBeanPostProcessor.postProcessMergedBeanDefinition()————InjectionMetadata metadata = findAutowiringMetadat…
- AutowiredAnnotationBeanPostProcessor.findAutowiringMetadata()————this.injectionMetadataCache.put(cacheKey, metadata…
断点三:根据元数据生成bean名称userService
代码块19:doCreateBean
再次回到doCreateBean方法,填充bean属性
参数:beanName=userController
参数:mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowi…
package org.springframework.beans.factory.support;
public class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory{
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {
......
"***********"instanceWrapper = createBeanInstance(beanName, mbd, args);
"(10)"
"*******************"applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
"(11)"
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
Object exposedObject = bean;
try {
"***********"populateBean(beanName, mbd, instanceWrapper);
"(19) 再次回到doCreateBean方法,填充bean属性"
"参数:beanName=userController"
"参数:mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\project\helloworld\target\classes\com\helloworld\controller\UserController.class]"
"参数:bw=org.springframework.beans.BeanWrapperImpl: wrapping object [com.helloworld.controller.UserController@17f7cd29]"
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
throw (BeanCreationException) ex;
}
else {
throw new BeanCreationException(
......
}
return exposedObject;
}
}
代码块20:populateBean
遍历所有的后置处理器,尤其是AutowiredAnnotationBeanPostProcessor
参数:beanName=userController
参数:mbd=Root bean: class [com.helloworld.controller.UserController]; scope=singleton; abstract=false; lazyInit=false; autowi…
参数:bw=org.springframework.beans.BeanWrapperImpl: wrapping object [com.helloworld.controller.UserController@17f7cd29]
package org.springframework.beans.factory.support;
public class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory{
@SuppressWarnings("deprecation")
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
if (bw == null) {
if (mbd.hasPropertyValues()) {
......
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
"*******************"PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
"(20) 遍历所有的后置处理器,尤其是AutowiredAnnotationBeanPostProcessor"
"参数:pvs=PropertyValues: length=0"
"参数:beanName=userController"
if (pvsToUse == null) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
return;
}
......
if (pvs != null) {
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
}
代码块21:postProcessProperties
使用自动装配元数据,执行依赖注入
参数:pvs=PropertyValues: length=0
参数:beanName=userController
package org.springframework.beans.factory.annotation;
public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor{
@Override
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
try {
"***********"metadata.inject(bean, beanName, pvs);
"(21) 使用自动装配元数据,执行依赖注入"
"参数:beanName=userController"
"参数:pvs=PropertyValues: length=0"
}
catch (BeanCreationException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
}
return pvs;
}
}
代码块22:inject
注入
参数:beanName=userController
参数:pvs=PropertyValues: length=0
package org.springframework.beans.factory.annotation;
public class InjectionMetadata {
public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
Collection<InjectedElement> checkedElements = this.checkedElements;
Collection<InjectedElement> elementsToIterate =
(checkedElements != null ? checkedElements : this.injectedElements);
if (!elementsToIterate.isEmpty()) {
for (InjectedElement element : elementsToIterate) {
if (logger.isTraceEnabled()) {
logger.trace("Processing injected element of bean '" + beanName + "': " + element);
}
"***************"element.inject(target, beanName, pvs);
"(22) 注入"
"参数:beanName=userController"
"参数:pvs=PropertyValues: length=0"
}
}
}
}
代码块23:inject
首先进行依赖分析
参数:beanName=userController
参数:pvs=PropertyValues: length=0
package org.springframework.beans.factory.annotation;
public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor{
@Override
protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
Field field = (Field) this.member;
Object value;
......
DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
desc.setContainingClass(bean.getClass());
Set<String> autowiredBeanNames = new LinkedHashSet<>(1);
Assert.state(beanFactory != null, "No BeanFactory available");
TypeConverter typeConverter = beanFactory.getTypeConverter();
try {
"*******************"value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
"(23) 首先进行依赖分析"
"参数:descriptor=field 'userService'"
"参数:requestingBeanName=userController"
}
catch (BeansException ex) {
throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex);
}
synchronized (this) {
if (!this.cached) {
if (value != null || this.required) {
this.cachedFieldValue = desc;
......
ReflectionUtils.makeAccessible(field);
field.set(bean, value);
}
}
}
代码块24:resolveDependency
依赖分析
参数:descriptor=field ‘userService’
参数:requestingBeanName=userController
package org.springframework.beans.factory.support;
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{
@Override
@Nullable
public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,
@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {
......
return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName);
}
else {
Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
descriptor, requestingBeanName);
if (result == null) {
"***************"result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
"(24) 依赖分析"
"参数:descriptor=field 'userService'"
"参数:beanName=userController"
}
return result;
}
}
}
代码块25:doResolveDependency
查找自动装配候选属性
参数:descriptor=field ‘userService’
参数:beanName=userController
package org.springframework.beans.factory.support;
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{
@Nullable
public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,
@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {
......
Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);
if (multipleBeans != null) {
return multipleBeans;
}
"***********"Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
"(25) 查找自动装配候选属性,第二个参数type,即是需要找到的自动装配候选者的类型com.helloworld.service.UserService。"
"参数:beanName=userController"
"参数:requiredType=interface com.helloworld.service.UserService"
"参数:descriptor=field 'userService'"
if (matchingBeans.isEmpty()) {
if (isRequired(descriptor)) {
raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
}
return null;
}
String autowiredBeanName;
......
finally {
ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
}
}
}
代码块26:findAutowireCandidates
根据类型获取候选属性名称
参数:beanName=userController
参数:requiredType=interface com.helloworld.service.UserService
参数:descriptor=field ‘userService’
package org.springframework.beans.factory.support;
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{
protected Map<String, Object> findAutowireCandidates(
@Nullable String beanName, Class<?> requiredType, DependencyDescriptor descriptor) {
"*******"String[] candidateNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
"(26) 根据类型获取候选属性名称"
"参数:lbf=org.springframework.beans.factory.support.DefaultListableBeanFactory@7960847b: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,demoApplication,testAspect,userController,myBeanPostProcessor,myBeanFactoryPostProcessor,userServiceImpl,user_zhangsan,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy"
"参数:type=interface com.helloworld.service.UserService"
"参数:includeNonSingletons=true"
"参数:allowEagerInit=true"
this, requiredType, true, descriptor.isEager());
Map<String, Object> result = new LinkedHashMap<>(candidateNames.length);
for (Map.Entry<Class<?>, Object> classObjectEntry : this.resolvableDependencies.entrySet()) {
Class<?> autowiringType = classObjectEntry.getKey();
if (autowiringType.isAssignableFrom(requiredType)) {
Object autowiringValue = classObjectEntry.getValue();
autowiringValue = AutowireUtils.resolveAutowiringValue(autowiringValue, requiredType);
if (requiredType.isInstance(autowiringValue)) {
......
}
}
return result;
}
}
代码块27:beanNamesForTypeIncludingAncestors
根据类型获取候选项名称userService
参数:lbf=org.springframework.beans.factory.support.DefaultListableBeanFactory@7960847b: defining beans [org.springframework.c…
参数:type=interface com.helloworld.service.UserService
参数:includeNonSingletons=true
参数:allowEagerInit=true
package org.springframework.beans.factory;
public class BeanFactoryUtils {
public static String[] beanNamesForTypeIncludingAncestors(
ListableBeanFactory lbf, Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) {
Assert.notNull(lbf, "ListableBeanFactory must not be null");
"*******"String[] result = lbf.getBeanNamesForType(type, includeNonSingletons, allowEagerInit);
"(27) 根据类型获取候选项名称userService"
"参数:type=interface com.helloworld.service.UserService"
"参数:includeNonSingletons=true"
"参数:allowEagerInit=true"
if (lbf instanceof HierarchicalBeanFactory) {
HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf;
if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) {
String[] parentResult = beanNamesForTypeIncludingAncestors(
(ListableBeanFactory) hbf.getParentBeanFactory(), type, includeNonSingletons, allowEagerInit);
result = mergeNamesWithParent(result, parentResult, hbf);
}
}
return result;
}
}
代码块28:getBeanNamesForType
根据类型获取候选项名称userService
参数:type=interface com.helloworld.service.UserService
参数:includeNonSingletons=true
参数:allowEagerInit=true
package org.springframework.beans.factory.support;
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{
@Override
public String[] getBeanNamesForType(@Nullable Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) {
if (!isConfigurationFrozen() || type == null || !allowEagerInit) {
return doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, allowEagerInit);
......
Map<Class<?>, String[]> cache =
(includeNonSingletons ? this.allBeanNamesByType : this.singletonBeanNamesByType);
String[] resolvedBeanNames = cache.get(type);
if (resolvedBeanNames != null) {
return resolvedBeanNames;
}
"*******"resolvedBeanNames = doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, true);
"(28) 根据类型获取候选项名称userService"
"参数:includeNonSingletons=true"
"参数:allowEagerInit=true"
if (ClassUtils.isCacheSafe(type, getBeanClassLoader())) {
cache.put(type, resolvedBeanNames);
}
return resolvedBeanNames;
}
}
代码块29:doGetBeanNamesForType
根据类型匹配beanName
参数:includeNonSingletons=true
参数:allowEagerInit=true
package org.springframework.beans.factory.support;
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{
private String[] doGetBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) {
List<String> result = new ArrayList<>();
......
BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();
boolean matchFound =
(allowEagerInit || !isFactoryBean ||
(dbd != null && !mbd.isLazyInit()) || containsSingleton(beanName)) &&
(includeNonSingletons ||
(dbd != null ? mbd.isSingleton() : isSingleton(beanName))) &&
"*******************************"isTypeMatch(beanName, type);
"(29) 循环所有的bean定义,根据类型匹配beanName"
if (!matchFound && isFactoryBean) {
beanName = FACTORY_BEAN_PREFIX + beanName;
matchFound = (includeNonSingletons || mbd.isSingleton()) && isTypeMatch(beanName, type);
}
if (matchFound) {
result.add(beanName);
}
......
}
return StringUtils.toStringArray(result);
}
}
总结:
断点三:根据元数据生成bean名称userService
- DemoApplication.main()————AnnotationConfigApplicationContext ctx = new Annot…
- AnnotationConfigApplicationContext.AnnotationConfigApplicationContext()————refresh();
- AbstractApplicationContext.refresh()————finishBeanFactoryInitialization(beanFactory);
- AbstractApplicationContext.finishBeanFactoryInitialization()————beanFactory.preInstantiateSingletons();
- DefaultListableBeanFactory.preInstantiateSingletons()————getBean(beanName);
- AbstractBeanFactory.getBean()————return doGetBean(name, null, null, false);
- AbstractBeanFactory.doGetBean()————sharedInstance = getSingleton(beanName, () -> {
- DefaultSingletonBeanRegistry.getSingleton()————singletonObject = singletonFactory.getObject();
- AbstractAutowireCapableBeanFactory.createBean()————Object beanInstance = doCreateBean(beanName, mbdTo…
- AbstractAutowireCapableBeanFactory.doCreateBean()————populateBean(beanName, mbd, instanceWrapper);
- AbstractAutowireCapableBeanFactory.populateBean()————PropertyValues pvsToUse = ibp.postProcessPropertie…
- AutowiredAnnotationBeanPostProcessor.postProcessProperties()————metadata.inject(bean, beanName, pvs);
- InjectionMetadata.inject()————element.inject(target, beanName, pvs);
- AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject()————value = beanFactory.resolveDependency(desc, beanNa…
- DefaultListableBeanFactory.resolveDependency()————result = doResolveDependency(descriptor, requestin…
- DefaultListableBeanFactory.doResolveDependency()————Map<String, Object> matchingBeans = findAutowireCa…
- DefaultListableBeanFactory.findAutowireCandidates()————String[] candidateNames = BeanFactoryUtils.beanNam…
- BeanFactoryUtils.beanNamesForTypeIncludingAncestors()————String[] result = lbf.getBeanNamesForType(type, in…
- DefaultListableBeanFactory.getBeanNamesForType()————resolvedBeanNames = doGetBeanNamesForType(Resolvab…
- DefaultListableBeanFactory.doGetBeanNamesForType()————isTypeMatch(beanName, type);
断点四:根据beanName查找创建userService对象
代码块30:doResolveDependency
获取beanName之后,回到doResolveDependency方法,生成候选组件userServiceImpl对象
参数:descriptor=field ‘userService’
参数:beanName=userController
package org.springframework.beans.factory.support;
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{
@Nullable
public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,
@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {
......
"***********"Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
"(25)"
}
if (autowiredBeanNames != null) {
autowiredBeanNames.add(autowiredBeanName);
}
if (instanceCandidate instanceof Class) {
"***************"instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this);
"(30) 获取beanName之后,回到doResolveDependency方法,生成候选组件userServiceImpl对象"
"参数:beanName=userServiceImpl"
"参数:requiredType=interface com.helloworld.service.UserService"
"参数:beanFactory=org.springframework.beans.factory.support.DefaultListableBeanFactory@7960847b: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,demoApplication,testAspect,userController,myBeanPostProcessor,myBeanFactoryPostProcessor,userServiceImpl,user_zhangsan,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy"
}
Object result = instanceCandidate;
if (result instanceof NullBean) {
if (isRequired(descriptor)) {
raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
}
result = null;
}
......
finally {
ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
}
}
}
代码块31:resolveCandidate
获取Bean
参数:beanName=userServiceImpl
参数:requiredType=interface com.helloworld.service.UserService
参数:beanFactory=org.springframework.beans.factory.support.DefaultListableBeanFactory@7960847b: defining beans [org.springfra…
package org.springframework.beans.factory.config;
public class DependencyDescriptor extends InjectionPoint implements Serializable{
public Object resolveCandidate(String beanName, Class<?> requiredType, BeanFactory beanFactory)
throws BeansException {
"*******"return beanFactory.getBean(beanName);
"(31) 获取Bean"
"参数:name=userServiceImpl"
}
}
代码块32:getBean
根据beanName获取userService对象
参数:name=userServiceImpl
package org.springframework.beans.factory.support;
public class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory{
@Override
public Object getBean(String name) throws BeansException {
"*******"return doGetBean(name, null, null, false);
"(32) 根据beanName获取userService对象,具体的获取过程是另外的主线,执行完这句,拿到userService对象"
}
}
总结:
断点四:根据beanName查找创建userService对象
- DemoApplication.main()————AnnotationConfigApplicationContext ctx = new Annot…
- AnnotationConfigApplicationContext.AnnotationConfigApplicationContext()————refresh();
- AbstractApplicationContext.refresh()————finishBeanFactoryInitialization(beanFactory);
- AbstractApplicationContext.finishBeanFactoryInitialization()————beanFactory.preInstantiateSingletons();
- DefaultListableBeanFactory.preInstantiateSingletons()————getBean(beanName);
- AbstractBeanFactory.getBean()————return doGetBean(name, null, null, false);
- AbstractBeanFactory.doGetBean()————sharedInstance = getSingleton(beanName, () -> {
- DefaultSingletonBeanRegistry.getSingleton()————singletonObject = singletonFactory.getObject();
- AbstractAutowireCapableBeanFactory.createBean()————Object beanInstance = doCreateBean(beanName, mbdTo…
- AbstractAutowireCapableBeanFactory.doCreateBean()————populateBean(beanName, mbd, instanceWrapper);
- AbstractAutowireCapableBeanFactory.populateBean()————PropertyValues pvsToUse = ibp.postProcessPropertie…
- AutowiredAnnotationBeanPostProcessor.postProcessProperties()————metadata.inject(bean, beanName, pvs);
- InjectionMetadata.inject()————element.inject(target, beanName, pvs);
- AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject()————value = beanFactory.resolveDependency(desc, beanNa…
- DefaultListableBeanFactory.resolveDependency()————result = doResolveDependency(descriptor, requestin…
- DefaultListableBeanFactory.doResolveDependency()————instanceCandidate = descriptor.resolveCandidate(au…
- DependencyDescriptor.resolveCandidate()————return beanFactory.getBean(beanName);
- AbstractBeanFactory.getBean()————return doGetBean(name, null, null, false);
断点五:userController和userService均创建完毕,执行依赖注入
代码块33:inject
回到inject方法,此时userController对象和userService对象均已经创建完毕,反射的方式执行属性注入
参数:beanName=userController
参数:pvs=PropertyValues: length=0
package org.springframework.beans.factory.annotation;
public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor{
@Override
protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
Field field = (Field) this.member;
Object value;
......
"*******************"value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
"(23)"
this.cached = true;
}
}
}
if (value != null) {
ReflectionUtils.makeAccessible(field);
"***************"field.set(bean, value);
"(33) 回到inject方法,此时userController对象和userService对象均已经创建完毕,反射的方式执行属性注入,完成@Autowired注解注入"
}
}
}
总结:
断点五:userController和userService均创建完毕,执行依赖注入
- DemoApplication.main()————AnnotationConfigApplicationContext ctx = new Annot…
- AnnotationConfigApplicationContext.AnnotationConfigApplicationContext()————refresh();
- AbstractApplicationContext.refresh()————finishBeanFactoryInitialization(beanFactory);
- AbstractApplicationContext.finishBeanFactoryInitialization()————beanFactory.preInstantiateSingletons();
- DefaultListableBeanFactory.preInstantiateSingletons()————getBean(beanName);
- AbstractBeanFactory.getBean()————return doGetBean(name, null, null, false);
- AbstractBeanFactory.doGetBean()————sharedInstance = getSingleton(beanName, () -> {
- DefaultSingletonBeanRegistry.getSingleton()————singletonObject = singletonFactory.getObject();
- AbstractAutowireCapableBeanFactory.createBean()————Object beanInstance = doCreateBean(beanName, mbdTo…
- AbstractAutowireCapableBeanFactory.doCreateBean()————populateBean(beanName, mbd, instanceWrapper);
- AbstractAutowireCapableBeanFactory.populateBean()————PropertyValues pvsToUse = ibp.postProcessPropertie…
- AutowiredAnnotationBeanPostProcessor.postProcessProperties()————metadata.inject(bean, beanName, pvs);
- InjectionMetadata.inject()————element.inject(target, beanName, pvs);
- AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject()————field.set(bean, value);
附录
出现省略号的源代码全文、注释及运行时变量
完整代码:refresh
package org.springframework.context.support;
public class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext{
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
prepareRefresh();
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
prepareBeanFactory(beanFactory);
try {
postProcessBeanFactory(beanFactory);
invokeBeanFactoryPostProcessors(beanFactory);
registerBeanPostProcessors(beanFactory);
initMessageSource();
initApplicationEventMulticaster();
onRefresh();
registerListeners();
finishBeanFactoryInitialization(beanFactory);
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
destroyBeans();
cancelRefresh(ex);
throw ex;
}
finally {
resetCommonCaches();
}
}
}
}
完整代码:finishBeanFactoryInitialization
package org.springframework.context.support;
public class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext{
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
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));
}
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
beanFactory.setTempClassLoader(null);
beanFactory.freezeConfiguration();
beanFactory.preInstantiateSingletons();
}
}
完整代码:preInstantiateSingletons
package org.springframework.beans.factory.support;
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{
@Override
public void preInstantiateSingletons() throws BeansException {
if (logger.isTraceEnabled()) {
logger.trace("Pre-instantiating singletons in " + this);
}
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
for (String beanName : beanNames) {
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
if (isFactoryBean(beanName)) {
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
if (bean instanceof FactoryBean) {
final FactoryBean<?> factory = (FactoryBean<?>) bean;
boolean isEagerInit;
if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
((SmartFactoryBean<?>) factory)::isEagerInit,
getAccessControlContext());
}
else {
isEagerInit = (factory instanceof SmartFactoryBean &&
((SmartFactoryBean<?>) factory).isEagerInit());
}
if (isEagerInit) {
getBean(beanName);
}
}
}
else {
getBean(beanName);
}
}
}
for (String beanName : beanNames) {
Object singletonInstance = getSingleton(beanName);
if (singletonInstance instanceof SmartInitializingSingleton) {
final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
smartSingleton.afterSingletonsInstantiated();
return null;
}, getAccessControlContext());
}
else {
smartSingleton.afterSingletonsInstantiated();
}
}
}
}
}
完整代码:doGetBean
package org.springframework.beans.factory.support;
public class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory{
@SuppressWarnings("unchecked")
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
final String beanName = transformedBeanName(name);
Object bean;
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isTraceEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
}
}
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
String nameToLookup = originalBeanName(name);
if (parentBeanFactory instanceof AbstractBeanFactory) {
return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
nameToLookup, requiredType, args, typeCheckOnly);
}
else if (args != null) {
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else if (requiredType != null) {
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
else {
return (T) parentBeanFactory.getBean(nameToLookup);
}
}
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
try {
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dep : dependsOn) {
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
registerDependentBean(dep, beanName);
try {
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, () -> {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
destroySingleton(beanName);
throw ex;
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
else if (mbd.isPrototype()) {
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
else {
String scopeName = mbd.getScope();
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, () -> {
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
});
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
throw new BeanCreationException(beanName,
"Scope '" + scopeName + "' is not active for the current thread; consider " +
"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
ex);
}
}
}
catch (BeansException ex) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}
if (requiredType != null && !requiredType.isInstance(bean)) {
try {
T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
if (convertedBean == null) {
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
return convertedBean;
}
catch (TypeMismatchException ex) {
if (logger.isTraceEnabled()) {
logger.trace("Failed to convert bean '" + name + "' to required type '" +
ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}
}
完整代码:getSingleton
package org.springframework.beans.factory.support;
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry{
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
synchronized (this.singletonObjects) {
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while singletons of this factory are in destruction " +
"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
}
if (logger.isDebugEnabled()) {
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
beforeSingletonCreation(beanName);
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
try {
singletonObject = singletonFactory.getObject();
newSingleton = true;
}
catch (IllegalStateException ex) {
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
throw ex;
}
}
catch (BeanCreationException ex) {
if (recordSuppressedExceptions) {
for (Exception suppressedException : this.suppressedExceptions) {
ex.addRelatedCause(suppressedException);
}
}
throw ex;
}
finally {
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
afterSingletonCreation(beanName);
}
if (newSingleton) {
addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
}
}
完整代码:createBean
package org.springframework.beans.factory.support;
public class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory{
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
if (logger.isTraceEnabled()) {
logger.trace("Creating instance of bean '" + beanName + "'");
}
RootBeanDefinition mbdToUse = mbd;
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
try {
mbdToUse.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}
try {
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
try {
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
}
}
}
完整代码:doCreateBean
package org.springframework.beans.factory.support;
public class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory{
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = instanceWrapper.getWrappedInstance();
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isTraceEnabled()) {
logger.trace("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
Object exposedObject = bean;
try {
populateBean(beanName, mbd, instanceWrapper);
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
throw (BeanCreationException) ex;
}
else {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
}
}
if (earlySingletonExposure) {
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
if (!actualDependentBeans.isEmpty()) {
throw new BeanCurrentlyInCreationException(beanName,
"Bean with name '" + beanName + "' has been injected into other beans [" +
StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
"] in its raw version as part of a circular reference, but has eventually been " +
"wrapped. This means that said other beans do not use the final version of the " +
"bean. This is often the result of over-eager type matching - consider using " +
"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
}
完整代码:findAutowiringMetadata
package org.springframework.beans.factory.annotation;
public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor{
private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) {
String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
if (InjectionMetadata.needsRefresh(metadata, clazz)) {
synchronized (this.injectionMetadataCache) {
metadata = this.injectionMetadataCache.get(cacheKey);
if (InjectionMetadata.needsRefresh(metadata, clazz)) {
if (metadata != null) {
metadata.clear(pvs);
}
metadata = buildAutowiringMetadata(clazz);
this.injectionMetadataCache.put(cacheKey, metadata);
}
}
}
return metadata;
}
}
完整代码:buildAutowiringMetadata
package org.springframework.beans.factory.annotation;
public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor{
private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {
List<InjectionMetadata.InjectedElement> elements = new ArrayList<>();
Class<?> targetClass = clazz;
do {
final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>();
ReflectionUtils.doWithLocalFields(targetClass, field -> {
AnnotationAttributes ann = findAutowiredAnnotation(field);
if (ann != null) {
if (Modifier.isStatic(field.getModifiers())) {
if (logger.isInfoEnabled()) {
logger.info("Autowired annotation is not supported on static fields: " + field);
}
return;
}
boolean required = determineRequiredStatus(ann);
currElements.add(new AutowiredFieldElement(field, required));
}
});
ReflectionUtils.doWithLocalMethods(targetClass, method -> {
Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
return;
}
AnnotationAttributes ann = findAutowiredAnnotation(bridgedMethod);
if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
if (Modifier.isStatic(method.getModifiers())) {
if (logger.isInfoEnabled()) {
logger.info("Autowired annotation is not supported on static methods: " + method);
}
return;
}
if (method.getParameterCount() == 0) {
if (logger.isInfoEnabled()) {
logger.info("Autowired annotation should only be used on methods with parameters: " +
method);
}
}
boolean required = determineRequiredStatus(ann);
PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
currElements.add(new AutowiredMethodElement(method, required, pd));
}
});
elements.addAll(0, currElements);
targetClass = targetClass.getSuperclass();
}
while (targetClass != null && targetClass != Object.class);
return new InjectionMetadata(clazz, elements);
}
}
完整代码:populateBean
package org.springframework.beans.factory.support;
public class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory{
@SuppressWarnings("deprecation")
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
if (bw == null) {
if (mbd.hasPropertyValues()) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
}
else {
return;
}
}
boolean continueWithPropertyPopulation = true;
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
continueWithPropertyPopulation = false;
break;
}
}
}
}
if (!continueWithPropertyPopulation) {
return;
}
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME || mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
PropertyDescriptor[] filteredPds = null;
if (hasInstAwareBpps) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
return;
}
}
pvs = pvsToUse;
}
}
}
if (needsDepCheck) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
checkDependencies(beanName, mbd, filteredPds, pvs);
}
if (pvs != null) {
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
}
完整代码:inject
package org.springframework.beans.factory.annotation;
public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor{
@Override
protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
Field field = (Field) this.member;
Object value;
if (this.cached) {
value = resolvedCachedArgument(beanName, this.cachedFieldValue);
}
else {
DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
desc.setContainingClass(bean.getClass());
Set<String> autowiredBeanNames = new LinkedHashSet<>(1);
Assert.state(beanFactory != null, "No BeanFactory available");
TypeConverter typeConverter = beanFactory.getTypeConverter();
try {
value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
}
catch (BeansException ex) {
throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex);
}
synchronized (this) {
if (!this.cached) {
if (value != null || this.required) {
this.cachedFieldValue = desc;
registerDependentBeans(beanName, autowiredBeanNames);
if (autowiredBeanNames.size() == 1) {
String autowiredBeanName = autowiredBeanNames.iterator().next();
if (beanFactory.containsBean(autowiredBeanName) &&
beanFactory.isTypeMatch(autowiredBeanName, field.getType())) {
this.cachedFieldValue = new ShortcutDependencyDescriptor(
desc, autowiredBeanName, field.getType());
}
}
}
else {
this.cachedFieldValue = null;
}
this.cached = true;
}
}
}
if (value != null) {
ReflectionUtils.makeAccessible(field);
field.set(bean, value);
}
}
}
完整代码:resolveDependency
package org.springframework.beans.factory.support;
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{
@Override
@Nullable
public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,
@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {
descriptor.initParameterNameDiscovery(getParameterNameDiscoverer());
if (Optional.class == descriptor.getDependencyType()) {
return createOptionalDependency(descriptor, requestingBeanName);
}
else if (ObjectFactory.class == descriptor.getDependencyType() ||
ObjectProvider.class == descriptor.getDependencyType()) {
return new DependencyObjectProvider(descriptor, requestingBeanName);
}
else if (javaxInjectProviderClass == descriptor.getDependencyType()) {
return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName);
}
else {
Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
descriptor, requestingBeanName);
if (result == null) {
result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
}
return result;
}
}
}
完整代码:doResolveDependency
package org.springframework.beans.factory.support;
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{
@Nullable
public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,
@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {
InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
try {
Object shortcut = descriptor.resolveShortcut(this);
if (shortcut != null) {
return shortcut;
}
Class<?> type = descriptor.getDependencyType();
Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);
if (value != null) {
if (value instanceof String) {
String strVal = resolveEmbeddedValue((String) value);
BeanDefinition bd = (beanName != null && containsBean(beanName) ?
getMergedBeanDefinition(beanName) : null);
value = evaluateBeanDefinitionString(strVal, bd);
}
TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
try {
return converter.convertIfNecessary(value, type, descriptor.getTypeDescriptor());
}
catch (UnsupportedOperationException ex) {
return (descriptor.getField() != null ?
converter.convertIfNecessary(value, type, descriptor.getField()) :
converter.convertIfNecessary(value, type, descriptor.getMethodParameter()));
}
}
Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);
if (multipleBeans != null) {
return multipleBeans;
}
Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
if (matchingBeans.isEmpty()) {
if (isRequired(descriptor)) {
raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
}
return null;
}
String autowiredBeanName;
Object instanceCandidate;
if (matchingBeans.size() > 1) {
autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor);
if (autowiredBeanName == null) {
if (isRequired(descriptor) || !indicatesMultipleBeans(type)) {
return descriptor.resolveNotUnique(descriptor.getResolvableType(), matchingBeans);
}
else {
return null;
}
}
instanceCandidate = matchingBeans.get(autowiredBeanName);
}
else {
Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next();
autowiredBeanName = entry.getKey();
instanceCandidate = entry.getValue();
}
if (autowiredBeanNames != null) {
autowiredBeanNames.add(autowiredBeanName);
}
if (instanceCandidate instanceof Class) {
instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this);
}
Object result = instanceCandidate;
if (result instanceof NullBean) {
if (isRequired(descriptor)) {
raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
}
result = null;
}
if (!ClassUtils.isAssignableValue(type, result)) {
throw new BeanNotOfRequiredTypeException(autowiredBeanName, type, instanceCandidate.getClass());
}
return result;
}
finally {
ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
}
}
}
完整代码:findAutowireCandidates
package org.springframework.beans.factory.support;
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{
protected Map<String, Object> findAutowireCandidates(
@Nullable String beanName, Class<?> requiredType, DependencyDescriptor descriptor) {
String[] candidateNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
this, requiredType, true, descriptor.isEager());
Map<String, Object> result = new LinkedHashMap<>(candidateNames.length);
for (Map.Entry<Class<?>, Object> classObjectEntry : this.resolvableDependencies.entrySet()) {
Class<?> autowiringType = classObjectEntry.getKey();
if (autowiringType.isAssignableFrom(requiredType)) {
Object autowiringValue = classObjectEntry.getValue();
autowiringValue = AutowireUtils.resolveAutowiringValue(autowiringValue, requiredType);
if (requiredType.isInstance(autowiringValue)) {
result.put(ObjectUtils.identityToString(autowiringValue), autowiringValue);
break;
}
}
}
for (String candidate : candidateNames) {
if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, descriptor)) {
addCandidateEntry(result, candidate, descriptor, requiredType);
}
}
if (result.isEmpty()) {
boolean multiple = indicatesMultipleBeans(requiredType);
DependencyDescriptor fallbackDescriptor = descriptor.forFallbackMatch();
for (String candidate : candidateNames) {
if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, fallbackDescriptor) &&
(!multiple || getAutowireCandidateResolver().hasQualifier(descriptor))) {
addCandidateEntry(result, candidate, descriptor, requiredType);
}
}
if (result.isEmpty() && !multiple) {
for (String candidate : candidateNames) {
if (isSelfReference(beanName, candidate) &&
(!(descriptor instanceof MultiElementDescriptor) || !beanName.equals(candidate)) &&
isAutowireCandidate(candidate, fallbackDescriptor)) {
addCandidateEntry(result, candidate, descriptor, requiredType);
}
}
}
}
return result;
}
}
完整代码:getBeanNamesForType
package org.springframework.beans.factory.support;
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{
@Override
public String[] getBeanNamesForType(@Nullable Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) {
if (!isConfigurationFrozen() || type == null || !allowEagerInit) {
return doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, allowEagerInit);
}
Map<Class<?>, String[]> cache =
(includeNonSingletons ? this.allBeanNamesByType : this.singletonBeanNamesByType);
String[] resolvedBeanNames = cache.get(type);
if (resolvedBeanNames != null) {
return resolvedBeanNames;
}
resolvedBeanNames = doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, true);
if (ClassUtils.isCacheSafe(type, getBeanClassLoader())) {
cache.put(type, resolvedBeanNames);
}
return resolvedBeanNames;
}
}
完整代码:doGetBeanNamesForType
package org.springframework.beans.factory.support;
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory{
private String[] doGetBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) {
List<String> result = new ArrayList<>();
for (String beanName : this.beanDefinitionNames) {
if (!isAlias(beanName)) {
try {
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
if (!mbd.isAbstract() && (allowEagerInit ||
(mbd.hasBeanClass() || !mbd.isLazyInit() || isAllowEagerClassLoading()) &&
!requiresEagerInitForType(mbd.getFactoryBeanName()))) {
boolean isFactoryBean = isFactoryBean(beanName, mbd);
BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();
boolean matchFound =
(allowEagerInit || !isFactoryBean ||
(dbd != null && !mbd.isLazyInit()) || containsSingleton(beanName)) &&
(includeNonSingletons ||
(dbd != null ? mbd.isSingleton() : isSingleton(beanName))) &&
isTypeMatch(beanName, type);
if (!matchFound && isFactoryBean) {
beanName = FACTORY_BEAN_PREFIX + beanName;
matchFound = (includeNonSingletons || mbd.isSingleton()) && isTypeMatch(beanName, type);
}
if (matchFound) {
result.add(beanName);
}
}
}
catch (CannotLoadBeanClassException ex) {
if (allowEagerInit) {
throw ex;
}
if (logger.isTraceEnabled()) {
logger.trace("Ignoring bean class loading failure for bean '" + beanName + "'", ex);
}
onSuppressedException(ex);
}
catch (BeanDefinitionStoreException ex) {
if (allowEagerInit) {
throw ex;
}
if (logger.isTraceEnabled()) {
logger.trace("Ignoring unresolvable metadata in bean definition '" + beanName + "'", ex);
}
onSuppressedException(ex);
}
}
}
for (String beanName : this.manualSingletonNames) {
try {
if (isFactoryBean(beanName)) {
if ((includeNonSingletons || isSingleton(beanName)) && isTypeMatch(beanName, type)) {
result.add(beanName);
continue;
}
beanName = FACTORY_BEAN_PREFIX + beanName;
}
if (isTypeMatch(beanName, type)) {
result.add(beanName);
}
}
catch (NoSuchBeanDefinitionException ex) {
if (logger.isTraceEnabled()) {
logger.trace("Failed to check manually registered singleton with name '" + beanName + "'", ex);
}
}
}
return StringUtils.toStringArray(result);
}
}
|