• Spring Ioc源码分析


    Spring Ioc 源码分析


    什么是Ioc

    在面对对象编程的开发过程中,以对象为核心,一个系统应用往往是由多个对象之间相互协作完成的。对象与对象之间耦合在一起,如果其中一个对象出现了问题或者需要发生改变的话,整个系统都可能会出现问题。想要解决这个问题,解决对象之间的耦合的话,就需要引用第三方来将这些具有依赖关系的对象进行解耦。
    这个第三方就是我们所说的Ioc容器了,它把所有的对象的控制权收归所有,将所有的对象粘合在一起。在没有引用ioc的系统里面,如果一个对象需要依赖另一个对象的时候,需要自己主动地去创建一个对象或者使用已创建的对象,控制器在自己的手中,引入Ioc容器之后,当一个对象需要依赖另一个对象的时候,不再需要自己主动去创建对象,Ioc容器会创建一个对象注入到需要使用的地方,这样对象的控制权颠倒过来了,所以叫作依赖反转了。

    Spring Ioc实现

    Spring通过BeanDefinition来管理基于Spring的应用的对象与他们之间的相互依赖关系,BeanDefinition是依赖反转中管理对象与对象之间依赖关系的数据抽象。Spring Ioc容器是通过围绕对BeanDefinition的处理来完成。
    beanFactory

    在Ioc容器的设计类图中,BeanFactory是Ioc容器的基类,它主要是定义Ioc容器的基本功能方法及规范。在HierarchicalBeanFactory中则定义getParentBeanFactory方法来获取双亲的容器的功能,让BeanFactory具有管理双亲容器的能力。ConfigurableBeanFactory接口的话,则提供了一些工具来配置BeanFactory。再看以ApplicationContext应用上下文接口为核心的接口设计,ApplicationContext继承了ListableBeanFactory、HierarchicalBeanFactory、AutowireCapableBeanFactory等BeanFactory接口,具有了BeanFactory Ioc容器的基本功能,还继承了MessageSource、ResourcePatternResolver、ApplicationEventPublisher接口,MessageSource提供了支持不同的信息源的功能,支持国际化的实现。ResourcePatternResolver接口提供了访问资源的功能、利用ResourceLoader和Resource可以从不同地方得到Bean定义资源。ApplicationEventPublisher接口提供了在上下文引入事件机制来管理Bean的生命周期。这些接口丰富Ioc容器的功能。

    Ioc容器初始化

    FileSystemXmlApplicationContext

    我们通过以FileSystemXmlApplicationContext为核心的继承体系,FileSystemXmlApplicationContext通过继承AbstractApplicationContext具备ResourceLoader加载Resource和Resource定义BeanDefinition的功能。
    Ioc容器的初始化是通过其构造函数的中的refresh()方法完成。。setConfigLocations()设置了定义BeanDefinition的Resource的Paths,它可以根据文件路径或者Url来创建不同的resource。通过refresh()方法实现了BeanDefinition的Resource定位、载入、注册过程.

    public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent) throws BeansException {
    		super(parent);
    		setConfigLocations(configLocations);
    		if (refresh) {
    			refresh();
    		}
    	}
    

    BeanDefinition的Resource定位

    Resource定位是BeanDefinition的资源定位,它通过ResourceLoader对Resource接口完成,Resource对各种形式的BeanDefinition使用提供了统一接口。refresh()方法是在AbstractApplicationContext中实现的。refresh方法通过调用obtainFreshBeanFactory创建一个Ioc容器来提供给ApplicationContext使用。在创建Ioc容器的过程中,它是调用AbstractRefreshableApplicationContext的refreshBeanFactory()方法来创建,refreshBeanFactory()中通过getInternalParentBeanFactory来获取双亲容器信息来生成Ioc容器DefaultListableBeanFactory,然后将Ioc容器传入loadBeanDefinitions方法来委托给子类来调用相应BeanDefinitions方法。loadBeanDefinitions是在AbstractXmlApplicationContext中实现的。它是通过传入的ioc容器来构建相应的ResourceLoader(默认为DefaultResourceLoader)和Environment,然后返回XmlBeanDefinitionReader,然后委托给XmlBeanDefinitionReader来loadBeanDefinition。在XmlBeanDefinitionReade的loadBeanDefinition方法中,根据Resource的路径是绝对路径还是模式匹配来选择ResourceLoader,使用对应的getResource方法对location进行解析来获取Resource集合,完成了Resource的定位。

    protected final void refreshBeanFactory() throws BeansException {
    	//判断是否已经存在beanFactory,存在就将beanFactory销毁。
    	if (hasBeanFactory()) {
    		destroyBeans();
    		closeBeanFactory();
    	}
    	//创建和设置DefaultListableBeanFactory,然后调用AbstractXmlApplicationContext中实现的
    	//loadBeanDefinitions方法。
    		DefaultListableBeanFactory beanFactory = createBeanFactory();
    		beanFactory.setSerializationId(getId());
    		customizeBeanFactory(beanFactory);
    		loadBeanDefinitions(beanFactory);
    		synchronized (this.beanFactoryMonitor) {
    			this.beanFactory = beanFactory;
    		}
    	}
    }
    
    protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
    	//创建XmlBeanDefinitionReader载入beanDefinition
    	XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
    	//通过上下文的资源载入环境信息在配置beanDefinitionReader
    	beanDefinitionReader.setEnvironment(this.getEnvironment());
    	beanDefinitionReader.setResourceLoader(this);
    	beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
        
    	initBeanDefinitionReader(beanDefinitionReader);
    	//委托给beanDefinitionReader来载入beanDefinition
    	loadBeanDefinitions(beanDefinitionReader);
    }
    
    public int loadBeanDefinitions(String location, Set<Resource> actualResources) throws BeanDefinitionStoreException {
    //获取ResourceLoader,使用的DefaultResourceLoader
    	ResourceLoader resourceLoader = getResourceLoader();
    	if (resourceLoader instanceof ResourcePatternResolver) {
    			Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
    			int loadCount = loadBeanDefinitions(resources);
    			if (actualResources != null) {
    				for (Resource resource : resources) {
    					actualResources.add(resource);
    				}
    			}
    			return loadCount;
    		}
    	}else {
    		Resource resource = resourceLoader.getResource(location);
    		int loadCount = loadBeanDefinitions(resource);
    		if (actualResources != null) {
    			actualResources.add(resource);
    		}
    		return loadCount;
    	}
    }
    
    public Resource getResource(String location) {
        //如果location是以classpath:开头的话,就构建ClassPathResource
    	if (location.startsWith(CLASSPATH_URL_PREFIX)) {
    		return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
    	}
    	else {
    		try {
    		    //默认以URL去解析location,
    			URL url = new URL(location);
    			return new UrlResource(url);
    		}
    		catch (MalformedURLException ex) {
    		    //如果以url形式去解析location失败,则构建ClassPathContextResource
    			return getResourceByPath(location);
    		}
    	}
    }
    

    BeanDefinition的载入和解析

    BeanDefinition的载入过程,就是把定义的BeanDefinition在Ioc容器转化为Spring的数据结构,通过HashMap来持有及维护。Ioc容器对Bean的管理和注入,是通过对BeanDefinition进行操作来实现的。对BeanDefinition的载入是Ioc容器初始化的一部分工作,refresh方法是Ioc容器的初始化入口。在在Resource的定位中,我们通过getResource来完成Resource的定位返回了Resource集合,然后BeanDefinition的载入则通过重载方法loadBeanDefinitions(Resource ..resources)的实现。Resource对象中封装了对文件的IO操作,可以直接打开IO来获取文件对象,然后通过documentLoader(默认为DefaultDocumentLoader)来解析文件来获取Document对象,documentLoader只是对通用的xml进行解析,并没有对Spring bean规则进行解析,Spring bean的解析是在DocumentReader(默认为DefaultBeanDefinitionDocumentReader,使用sax来解析xml)调用doRegisterBeanDefinitions委托给BeanDefinitionParserDelegate实现的。BeanDefinitionParserDelegate通过对各种Spring bean定义规则的处理和解析,在解析完成之后放到BeanDefinition对象中并由BeanDefinitionHolder持有。
    BeanDefinitionParserDelegate类有对各种property属性的解析方法,有兴趣的可以自己去查看。

    public void refresh() throws BeansException, IllegalStateException {
    	synchronized (this.startupShutdownMonitor) {
    		prepareRefresh();
    		ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
            //通过上下文对beanFactory进行前置处理
    		prepareBeanFactory(beanFactory);
    		try {
                //beanFactory的后置处理设置
    			postProcessBeanFactory(beanFactory);
    			//调用beanFactory的后置处理器
                invokeBeanFactoryPostProcessors(beanFactory);
                //根据bean的配置,注册bean后置处理器,在bean创建期间调用
    			registerBeanPostProcessors(beanFactory);
    			//对消息源进行初始化
    			initMessageSource();
    			//初始化上下文的事件机制
    			initApplicationEventMulticaster();
    			onRefresh();
    			//注册监听器
    			registerListeners();
    			//对配置了not-lazy-init的单例对象进行初始化
    			finishBeanFactoryInitialization(beanFactory);
    			//发布事件,结束refresh过程。
    			finishRefresh();
    		}catch (BeansException ex) {
    		    //如果初始化失败,会销毁所有已经创建的bean
    			destroyBeans();
                //重置标志位
    			cancelRefresh(ex);
    			throw ex;
    		}
    	}
    }
    
    //调用入口方法
    public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
    	return loadBeanDefinitions(new EncodedResource(resource));
    }
    
    public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
    	Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
    	if (currentResources == null) {
    		currentResources = new HashSet<EncodedResource>(4);
    		this.resourcesCurrentlyBeingLoaded.set(currentResources);
    	}
    	try {
    	//获取xml文件的IO流
    		InputStream inputStream = encodedResource.getResource().getInputStream();
    		try {
    		    //获取IO的InputResource,准备读取
    			InputSource inputSource = new InputSource(inputStream);
    			if (encodedResource.getEncoding() != null) {
    				inputSource.setEncoding(encodedResource.getEncoding());
    			}
    			//具体的读取过程在doLoadBeanDefinitions方法实现
    			return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
    		}
    		finally {
    			inputStream.close();
    		}
    	}finally {
    		currentResources.remove(encodedResource);
    		if (currentResources.isEmpty()) {
    			this.resourcesCurrentlyBeingLoaded.remove();
    		}
    	}
    }
    
    protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
    	throws BeanDefinitionStoreException {
            //调用documentLoader来解析获取Document对象。(DefaultDocumentLoader)
    		Document doc = doLoadDocument(inputSource, resource);
    		//根据Spring bean定义的规则对beanDefinition的解析过程。
    		return registerBeanDefinitions(doc, resource);
       }
    //根据Document对象来注册BeanDefinition
    public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
            //构建BeanDefinitionDocumentReader
    		BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
    		documentReader.setEnvironment(this.getEnvironment());
    		int countBefore = getRegistry().getBeanDefinitionCount();
    		//调用BeanDefinitionDocumentReader进行解析
    		documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
    		return getRegistry().getBeanDefinitionCount() - countBefore;
    	}
    	//BeanDefinition解析的入口类,传入Document的root节点。
    protected void doRegisterBeanDefinitions(Element root) {
    	String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
    	if (StringUtils.hasText(profileSpec)) {
    		String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
    				profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
    		if (!this.environment.acceptsProfiles(specifiedProfiles)) {
    			return;
    		}
    	}
    	/*
    	beans节点嵌套导致doRegisterBeanDefinitions递归调用,为了正确的保存beans(default-*)属性,保存当前的delegate(parent),创建一个新的delegate(children)保存指向parent的引用,使用delegate(children)来解析beanDefinition,然后再将delegate指向parent。
    	*/
    	BeanDefinitionParserDelegate parent = this.delegate;
    	this.delegate = createDelegate(this.readerContext, root, parent);
    
    	preProcessXml(root);
    	//解析BeanDefinition
    	parseBeanDefinitions(root, this.delegate);
    	postProcessXml(root);
    
    	this.delegate = parent;
    }
    	//对于import alias、bean、等节点解析。
    protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
    	if (delegate.isDefaultNamespace(root)) {
    		NodeList nl = root.getChildNodes();
    		for (int i = 0; i < nl.getLength(); i++) {
    			Node node = nl.item(i);
    			if (node instanceof Element) {
    				Element ele = (Element) node;
    				if (delegate.isDefaultNamespace(ele)) {
    					parseDefaultElement(ele, delegate);
    				}
    				else {
    					delegate.parseCustomElement(ele);
    				}
    			}
    		}
    	}
    	else {
    		delegate.parseCustomElement(root);
    	}
    }
        //根据不同节点选择不同的method进行调用
    private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
    	if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
    		importBeanDefinitionResource(ele);
    	}
    	else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
    		processAliasRegistration(ele);
    	}
    	else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
    		processBeanDefinition(ele, delegate);
    	}
    	else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
    		doRegisterBeanDefinitions(ele);
    	}
    }
    //对Bean节点的解析    	
    protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
    	//解析返回beanDefinition并由BeanDefinitionHolder持有
    		BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
    		if (bdHolder != null) {
    		    //对beanDefinitionHolder进行装饰
    			bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
    			//注册BeanDefinition
    			BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
    			getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
    		}
    	}
    	
    	
    public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, BeanDefinition containingBean) {
        //获取bean节点的id name和aliases的属性值
    	String id = ele.getAttribute(ID_ATTRIBUTE);
    	String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);
    
    	List<String> aliases = new ArrayList<String>();
    	if (StringUtils.hasLength(nameAttr)) {
    		String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS);
    		aliases.addAll(Arrays.asList(nameArr));
    	}
    
    	String beanName = id;
    	if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) {
    		beanName = aliases.remove(0);
    	}
    
    	if (containingBean == null) {
    		checkNameUniqueness(beanName, aliases, ele);
    	}
        //对beanDefinition进行解析
    	AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);
    	if (beanDefinition != null) {
    		if (!StringUtils.hasText(beanName)) {
    				if (containingBean != null) {
    					beanName = BeanDefinitionReaderUtils.generateBeanName(
    							beanDefinition, this.readerContext.getRegistry(), true);
    				}
    				else {
    					beanName = this.readerContext.generateBeanName(beanDefinition);
    					String beanClassName = beanDefinition.getBeanClassName();
    					if (beanClassName != null &&
    							beanName.startsWith(beanClassName) && beanName.length() >beanClassName.length() &&!this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) {
    						aliases.add(beanClassName);
    					}
    				}
    			}
    		}
    		String[] aliasesArray = StringUtils.toStringArray(aliases);
    		return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
    	}
    
    	return null;
    }
    
    public AbstractBeanDefinition parseBeanDefinitionElement(
    	Element ele, String beanName, BeanDefinition containingBean) {
    
    	this.parseState.push(new BeanEntry(beanName));
    
    	String className = null;
    	//获取className
    	if (ele.hasAttribute(CLASS_ATTRIBUTE)) {
    		className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
    	}
    
    	try {
    		String parent = null;
    		if (ele.hasAttribute(PARENT_ATTRIBUTE)) {
    			parent = ele.getAttribute(PARENT_ATTRIBUTE);
    		}
    		//创建Beandefinition对象
    		AbstractBeanDefinition bd = createBeanDefinition(className, parent);
            //对对应的bean属性解析,并设置description
    		parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
    		bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));
            //解析元数据和元素信息解析
    		parseMetaElements(ele, bd);
    		parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
    		parseReplacedMethodSubElements(ele, bd.getMethodOverrides());
    
    		parseConstructorArgElements(ele, bd);
    		parsePropertyElements(ele, bd);
    		parseQualifierElements(ele, bd);
    
    		bd.setResource(this.readerContext.getResource());
    		bd.setSource(extractSource(ele));
    
    		return bd;
    	}finally {
    		this.parseState.pop();
    	}
    	return null;
    }
    

    BeanDefinition在Ioc容器中的注册

    对BeanDefinition进行载入和解析之后,只是静态的配置信息,要发挥Ioc容器作用,需要在Ioc容器进行注册。Ioc容器通过维护一个HashMap来持有BeanDefinition,注册BeanDefinition是在BeanDefinitionParserDelegate解析beanDefinition之后,通过BeanDefinitionReaderUtils工具类registerBeanDefinition将BeanDefinition注册到Ioc容器中,它是委托给BeanDefinitionRegistry通过传入的beanFactory(DefaultListableBeanFactory实现了BeanDefinitionRegistry接口)来注册。
    完成BeanDefinition的注册,Ioc容器初始化就基本结束了,此时Ioc容器已经持有了BeanDefinition的配置信息,Ioc容器对Bean的管理就是通过对Beandefinition的操作来实现的。

    //删除了日志信息和异常处理,修改了部分源码,方便阅读
    public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
    		throws BeanDefinitionStoreException {
    	//验证beanDefinition信息
    	if (beanDefinition instanceof AbstractBeanDefinition) {
    			((AbstractBeanDefinition) beanDefinition).validate();
    	}
    	//为了保证数据的一致,使用了synchronized加锁进行同步
    	synchronized (this.beanDefinitionMap) {
    		BeanDefinition oldBeanDefinition = this.beanDefinitionMap.get(beanName);
    	
    		if (oldBeanDefinition == null) {
    			this.beanDefinitionNames.add(beanName);
    			this.frozenBeanDefinitionNames = null;
    		}
    		this.beanDefinitionMap.put(beanName, beanDefinition);
    	}
    	resetBeanDefinition(beanName);
    }
    

    Ioc容器的依赖注入

    除了设置了not-lazy-init的bean,其他bean的依赖注入是在用户对Ioc容器第一个请求获取Bean的时候触发的。
    因此getBean方法是依赖注入的入口方法,我们可以通过AbstractBeanFactory来查看getBean的实现。在getBean方法,首先对要创建的bean是不是已经创建的单例对象,如果是就不会重新构建,否则就利用bean的BeanDefinition根据不同的bean类型来调用createBean方法。createBean方法是在AbstractAutowireCapableBeanFactory中实现。在创建bean中,主要的是bean的实例化和bean属性的依赖关系处理

    public Object getBean(String name, Object... args) throws BeansException {
    	return doGetBean(name, null, args, false);
    }
    
    protected <T> T doGetBean(final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
    		throws BeansException {
    	final String beanName = transformedBeanName(name);
    	Object bean;
    	//从已经创建的bean缓存中去获取bean,如果是已经创建过的单例bean就不需要再次创建。
    	Object sharedInstance = getSingleton(beanName);
    	if (sharedInstance != null && args == null) {
    	    //根据是否为FactoryBean进行相关处理
    		bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
    	}
    	else {
    	//对BeanFactory中是否存在对应BeanDefinition,如果没有的话,就去双亲BeanFactory中去查找,会一直
    	//向双亲BeanFactory链中往上寻找
    		BeanFactory parentBeanFactory = getParentBeanFactory();
    		if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
    			String nameToLookup = originalBeanName(name);
    			if (args != null) {
    				return (T) parentBeanFactory.getBean(nameToLookup, args);
    			}
    			else {
    				return parentBeanFactory.getBean(nameToLookup, requiredType);
    			}
    		}
    		if (!typeCheckOnly) {
    			markBeanAsCreated(beanName);
    		}
    		try {
    		    //根据beanName获取对应的BeanDefinition。
    			final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
    			checkMergedBeanDefinition(mbd, beanName, args);
                //获取bean的所有依赖bean,会导致递归调用getBean,直到没有依赖Bean
    			String[] dependsOn = mbd.getDependsOn();
    			if (dependsOn != null) {
    				for (String dependsOnBean : dependsOn) {
    					if (isDependent(beanName, dependsOnBean)) {
    					}
    					registerDependentBean(dependsOnBean, beanName);
    					getBean(dependsOnBean);
    				}
    			}
    			//通过回调方法调用createBean创建单例对象
    			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);
    			}
    			//获取Prototype对象
    			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 {
    			    //request和session范围的bean
    				String scopeName = mbd.getScope();
    				final Scope scope = this.scopes.get(scopeName);
    				try {
    					Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {
    						@Override
    						public Object getObject() throws BeansException {
    							beforePrototypeCreation(beanName);
    							try {
    								return createBean(beanName, mbd, args);
    							}
    							finally {
    								afterPrototypeCreation(beanName);
    							}
    						}
    					});
    					bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
    				}
    				catch (IllegalStateException ex) {
    				
    				}
    			}
    		}
    		catch (BeansException ex) {
    			cleanupAfterBeanCreationFailure(beanName);
    			throw ex;
    		}
    	}
        //对bean类型进行类型检查
    	if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
    			return getTypeConverter().convertIfNecessary(bean, requiredType);
    	}
    	return (T) bean;
    }
    	
    protected Object createBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) throws BeanCreationException {
        	//判断类是否可以实例化(抽象类和接口不可实例化)
    		resolveBeanClass(mbd, beanName);
    		mbd.prepareMethodOverrides();
    		//如果Bean配置了PostProcessor,将会返回一个Proxy对象。
    		Object bean = resolveBeforeInstantiation(beanName, mbd);
    		if (bean != null) {
    			return bean;
    		}
    		//创建bean入口
    		Object beanInstance = doCreateBean(beanName, mbd, args);
    		return beanInstance;
    	}
    
    protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
    	//用来持有创建的bean对象
    	BeanWrapper instanceWrapper = null;
    	//如果是单例bean,要将缓存中的同名bean清除
    	if (mbd.isSingleton()) {
    		instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
    	}
    	//创建bean
    	if (instanceWrapper == null) {
    		instanceWrapper = createBeanInstance(beanName, mbd, args);
    	}
    	final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
    	Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
    	synchronized (mbd.postProcessingLock) {
    		if (!mbd.postProcessed) {
    			applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
    			mbd.postProcessed = true;
    		}
    	}
    	boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
    			isSingletonCurrentlyInCreation(beanName));
    	if (earlySingletonExposure) {
    		addSingletonFactory(beanName, new ObjectFactory<Object>() {
    			@Override
    			public Object getObject() throws BeansException {
    				return getEarlyBeanReference(beanName, mbd, bean);
    			}
    		});
    	}
    	Object exposedObject = bean;
    	//对bean进行初始化,对bean的属性进行配置和依赖注入,返回的exposeObject是依赖注入后的bean
    	populateBean(beanName, mbd, instanceWrapper);
    	if (exposedObject != null) {
    		exposedObject = initializeBean(beanName, exposedObject, mbd);
    	}
    	}
    
    	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<String>(dependentBeans.length);
    				for (String dependentBean : dependentBeans) {
    					if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
    						actualDependentBeans.add(dependentBean);
    					}
    				}
    			}
    		}
    	}
    	registerDisposableBeanIfNecessary(beanName, bean, mbd);
    	return exposedObject;
    }
    

    实例化Bean对象

    实例化Bean对象是在createBeanInstance中完成的,bean对象的生成可以通过工厂方法、autowire、构造器方法生成,可以通过配置Beandefinition来指定。对象生成的具体实现,如果有兴趣可以自行阅读源码,现暂不分析。

    protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
            //获取要创建的Bean的Class对象
    	Class<?> beanClass = resolveBeanClass(mbd, beanName);
    	//使用工厂方法对bean进行实例化
    	if (mbd.getFactoryMethodName() != null)  {
    		return instantiateUsingFactoryMethod(beanName, mbd, args);
    	}
    	boolean resolved = false;
    	boolean autowireNecessary = false;
    	if (args == null) {
    		synchronized (mbd.constructorArgumentLock) {
    			if (mbd.resolvedConstructorOrFactoryMethod != null) {
    				resolved = true;
    				autowireNecessary = mbd.constructorArgumentsResolved;
    			}
    		}
    	}
    	if (resolved) {
    		if (autowireNecessary) {
    		   //通过type进行autowire
    			return autowireConstructor(beanName, mbd, null, null);
    		}
    		else {
    		//使用默认策略来生成bean对象,既通过gclib来对bean进行实例化
    			return instantiateBean(beanName, mbd);
    		}
    	}
    	//根据传入参数来选择对应的构造器函数来实例化bean对象
    	Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
    	if (ctors != null ||
    			mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
    			mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args))  {
    		return autowireConstructor(beanName, mbd, ctors, args);
    	}
    	return instantiateBean(beanName, mbd);
    }
    

    配置依赖关系和依赖注入

    Bean的依赖关系通过BeanDefinition来处理,BeanDefinitionValueResolver对BeanDefinition进行解析,BeanWrapperImpl进行依赖注入

    protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
    //获取在BeanDefinition中设置的property值,如果propertyValues为空则立即返回
    	PropertyValues pvs = mbd.getPropertyValues();
    	if (bw == null) {
    		if (pvs.isEmpty()) {
    			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;
    	}
    	//依赖注入过程开始,首先对autowire先进行处理。
    	if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
    			mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
    		MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
    		//根据name注入
    		if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
    			autowireByName(beanName, mbd, bw, newPvs);
    		}
    		//根据type注入
    		if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
    			autowireByType(beanName, mbd, bw, newPvs);
    		}
    		pvs = newPvs;
    	}
    	boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
    	boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);
    	if (hasInstAwareBpps || needsDepCheck) {
    		PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
    		if (hasInstAwareBpps) {
    			for (BeanPostProcessor bp : getBeanPostProcessors()) {
    				if (bp instanceof InstantiationAwareBeanPostProcessor) {
    					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
    					pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
    					if (pvs == null) {
    						return;
    					}
    				}
    			}
    		}
    		if (needsDepCheck) {
    			checkDependencies(beanName, mbd, filteredPds, pvs);
    		}
    	}
    	//对属性开始注入
    	applyPropertyValues(beanName, mbd, bw, pvs);
    }
    
    protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
    	if (pvs == null || pvs.isEmpty()) {
    		return;
    	}
    
    	MutablePropertyValues mpvs = null;
    	List<PropertyValue> original;
    
    	if (System.getSecurityManager() != null) {
    		if (bw instanceof BeanWrapperImpl) {
    			((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
    		}
    	}
    
    	if (pvs instanceof MutablePropertyValues) {
    		mpvs = (MutablePropertyValues) pvs;
    		if (mpvs.isConverted()) {
    			bw.setPropertyValues(mpvs);
    			return;
    		}
    		original = mpvs.getPropertyValueList();
    	}
    	else {
    		original = Arrays.asList(pvs.getPropertyValues());
    	}
    
    	TypeConverter converter = getCustomTypeConverter();
    	if (converter == null) {
    		converter = bw;
    	}
    	BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);
    	//对解析值创建一个副本。
    	List<PropertyValue> deepCopy = new ArrayList<PropertyValue>(original.size());
    	boolean resolveNecessary = false;
    	for (PropertyValue pv : original) {
    		if (pv.isConverted()) {
    			deepCopy.add(pv);
    		}
    		else {
    			String propertyName = pv.getName();
    			Object originalValue = pv.getValue();
    			Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
    			Object convertedValue = resolvedValue;
    			boolean convertible = bw.isWritableProperty(propertyName) &&
    					!PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
    			if (convertible) {
    				convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
    			}
    			if (resolvedValue == originalValue) {
    				if (convertible) {
    					pv.setConvertedValue(convertedValue);
    				}
    				deepCopy.add(pv);
    			}
    			else if (convertible && originalValue instanceof TypedStringValue &&
    					!((TypedStringValue) originalValue).isDynamic() &&
    					!(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
    				pv.setConvertedValue(convertedValue);
    				deepCopy.add(pv);
    			}
    			else {
    				resolveNecessary = true;
    				deepCopy.add(new PropertyValue(pv, convertedValue));
    			}
    		}
    	}
    	if (mpvs != null && !resolveNecessary) {
    		mpvs.setConverted();
    	}
    	//依赖注入,通过BeanWrapperImplementation完成
    	bw.setPropertyValues(new MutablePropertyValues(deepCopy));
    }
  • 相关阅读:
    ListView Item 点击展开隐藏问题
    01背包基础 (杭电2602)
    实现一个简单的语音聊天室(多人语音聊天系统)
    Tomcat全攻略
    Linux pipe函数
    从网页抓取数据的一般方法
    华为的面试经历
    微软2014校园招聘笔试试题
    C++ 虚函数表解析
    unity3d 改动gui label颜色,定义颜色需除以256
  • 原文地址:https://www.cnblogs.com/xianyijun/p/5339115.html
Copyright © 2020-2023  润新知