博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
spring源码分析
阅读量:4230 次
发布时间:2019-05-26

本文共 98961 字,大约阅读时间需要 329 分钟。

spring在我们的java开发中使用很多,IOC作为spring最基础的组件,被大家所熟知,但是spring具体是怎么使用这个特性的呢?,本文主要讲解一下IOC的注册过程。从spring的启动开始,这里没有使用mvc的模块,主要是想单独分离出来讲IOC.

预先学习

这里是一个很简单的例子,但是对于理解spring的ioc很重要,一定要先读完哦,这个就是一个很简单的springioc过程。

public class XmlMain {    public static void main(String[] args) throws Exception {        XmlMain xmlMain = new XmlMain();        //解析xml,获取bean定义        Map
map = xmlMain.parseXml(); //student的定义 BeanDefinition studentDefinition = map.get("student"); //生成student对象 Object object = xmlMain.loadBean(studentDefinition); //设置student对象属性 xmlMain.setProperty(object, studentDefinition); //使用student Student student = (Student) object; student.print(); } /** * 解析bean * * @return key->beanName,value->bean的定义 * @throws Exception */ public Map
parseXml() throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); File file = ResourceUtils.getFile("classpath:parseTest.xml"); //读取配置文件 Document d = builder.parse(file); //获取所有bean节点 NodeList nodeList = d.getElementsByTagName(BeanDefinitionParserDelegate.BEAN_ELEMENT); Map
map = new HashMap
(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; //解析节点属性 String id = element.getAttribute(BeanDefinitionParserDelegate.ID_ATTRIBUTE); String className = element.getAttribute(BeanDefinitionParserDelegate.CLASS_ATTRIBUTE); AbstractBeanDefinition beanDefinition = BeanDefinitionReaderUtils.createBeanDefinition( null, className, null); NodeList childrenList = element.getChildNodes(); MutablePropertyValues mutablePropertyValues = new MutablePropertyValues(); for (int j = 0; j < childrenList.getLength(); j++) { Node children = childrenList.item(j); if (children.getNodeType() == Node.ELEMENT_NODE) { //解析子property节点 Element childrenElement = (Element) children; String name = childrenElement.getAttribute(BeanDefinitionParserDelegate.NAME_ATTRIBUTE); String value = childrenElement.getAttribute(BeanDefinitionParserDelegate.VALUE_ATTRIBUTE); mutablePropertyValues.add(name, value); } } beanDefinition.setPropertyValues(mutablePropertyValues); map.put(id, beanDefinition); } } return map; } /** * 创建bean * * @param beanDefinition * @return * @throws Exception */ public Object loadBean(BeanDefinition beanDefinition) throws Exception { Class
clazz = Class.forName(beanDefinition.getBeanClassName()); Constructor
constructorToUse; //获取默认构造方法 constructorToUse = clazz.getDeclaredConstructor(); return constructorToUse.newInstance(); } /** * 属性赋值,spring的远比这个复杂 * * @param object * @param beanDefinition * @return * @throws Exception */ public Object setProperty(Object object, BeanDefinition beanDefinition) throws Exception { MutablePropertyValues mutablePropertyValues = beanDefinition.getPropertyValues(); //获取obj类的字节文件对象 Class
c = object.getClass(); List
list = mutablePropertyValues.getPropertyValueList(); for (PropertyValue x : list) { //获取该类的成员变量 Field f = c.getDeclaredField(x.getName()); //取消语言访问检查 f.setAccessible(true); //给变量赋值 f.set(object, x.getValue()); } return object; }}

看完大概就知道什么意思了,对于理解spring很重要,下面开始吧。

例子

这里讲一个最最简单的例子,用来引出本文。

依赖

org.springframework
spring-context
4.3.11.RELEASE

配置文件

这里定义了一个很简单的bean,这个类的代码就不贴了。

启动spring

public class Main {    public static void main(String[] args) {        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:bean.xml");        HelloService helloService = applicationContext.getBean(HelloService.class);        System.out.println(helloService.hello("占旭鹏"));    }}

查看一下控制台:

hello ,占旭鹏

到这里为止,我们的例子就结束了,我们没有手动创建HelloService实例,而是通过spring创建的,我们可以获取到spring创建的实例并调用方法。

ClassPathXmlApplicationContext简介

先来看一张ClassPathXmlApplicationContext的继承关系图。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-oHjtTfxN-1573273794262)(EA57332F816948FEAB52BD5A39562288)]
从这个继承关系里面,我们可以获取到一些信息。

  1. AbstractApplicationContext是springIOC最主要的类,主要用于实现IOC的一些最基础的功能。
  2. AbstractRefreshableApplicationContext在父类的基础上新增了可刷新功能。
  3. AbstractRefreshableConfigApplicationContext在父类的基础上新增了可以刷新配置的功能(主要通过InitializingBean接口实现)。
  4. AbstractXmlApplicationContext在父类的基础上新增了解析xml中bean配置的功能。
  5. ClassPathXmlApplicationContext在父类的基础上新增了可以解析classpath路径下资源的功能。

ApplicationContext简介

我们刚刚通过applicationContext.getBean获取到了我们想要的bean,我们查看源码可以看到,这其实是BeanFatory的一个方法。BeanFactory从名字上我们就可以理解,这个类主要用于生产和管理Bean。ApplicationContext在BeanFactory的基础上做了一些扩展。

下面我们来看一下ApplicationContext的继承结构。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Y4lhs64M-1573273794265)(33BA9217760642E7B35369312B854D30)]

  1. EnvironmentCapable主要用于处理一些和环境配置的相关信息,比如我们可以配置local,dev等环境,分开配置。
  2. MessageSource主要用于国际化的。
  3. ApplicationEventPublisher用于发布事件。
  4. ResourcePatternResolver主要用于解析资源。
  5. ListableBeanFactory继承自BeanFactory,Listable是可列举的意思,看下新增的方法,里面主要是一些方法,可以根据条件返回多个bean。BeanFactory里面返回的都是单个的。
  6. HierarchicalBeanFactory继承自BeanFactory,Hierarchical是分等级的意思,查看新增的方法,可以看到,里面返回了parentBeanFactory,这个接口主要用于在应用中有个多BeanFactory时,可以设置父子关系。

分析

下面是代码分析,大家可以打开源码跟着看。我们从创建一个ClassPathXmlApplicationContext实例开始。

最后发现,调用了如下构造方法。这里parent为null,refresh为true。

public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)			throws BeansException {                //因为我们进来的时候是null,所有这里是null,查看父类方法我们发现就赋值了一下,没有其他事情。		super(parent);		//这里设置了一下配置文件的路径。里面的细节,我下面还会再讲。 		setConfigLocations(configLocations);				if (refresh) {		    //这个是重点,所有的事情都是在这里干的,里面包含整个ioc的初始化过程,		    //这里为什么用refresh而不是init时因为我们看接口继承关系可以知道,我们的应用是可以刷新的,		    //这里主要是考虑复用吧。			refresh();		}	}

我们先看一个例子

//往jvm虚拟机参数中加入一个环境变量-Dtest=bean//启动springpublic class Main {    public static void main(String[] args) {        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:${test}.xml");        HelloService helloService = applicationContext.getBean(HelloService.class);        System.out.println(helloService.hello("占旭鹏"));    }}

这里的${test}会被替换成bean,所以全路径就是classpath:bean.xml,setConfigLocations里面就是做了这些事情。

我们来看下setConfigLocations。

public void setConfigLocations(String... locations) {		if (locations != null) {			Assert.noNullElements(locations, "Config locations must not be null");			this.configLocations = new String[locations.length];			for (int i = 0; i < locations.length; i++) {				this.configLocations[i] = resolvePath(locations[i]).trim();			}		}		else {			this.configLocations = null;		}	}

从以上代码可以看出,这里就是对我们传入的路径做了一下解析,然后赋值保存下来了,这里需要重点看一下resolvePath方法。一直往里看,我们可以发现,最后是调用了PropertyPlaceholderHelper的parseStringValue方法。下面的代码就是具体的解析过程。

protected String parseStringValue(			String value, PlaceholderResolver placeholderResolver, Set
visitedPlaceholders) { StringBuilder result = new StringBuilder(value); //placeholderPrefix为${,找到${的位置 int startIndex = value.indexOf(this.placeholderPrefix); while (startIndex != -1) { //找到}的位置 int endIndex = findPlaceholderEndIndex(result, startIndex); if (endIndex != -1) { //获取${}之间的内容 String placeholder = result.substring(startIndex + this.placeholderPrefix.length(), endIndex); String originalPlaceholder = placeholder; if (!visitedPlaceholders.add(originalPlaceholder)) { throw new IllegalArgumentException( "Circular placeholder reference '" + originalPlaceholder + "' in property definitions"); } // Recursive invocation, parsing placeholders contained in the placeholder key. //这里递推了一下,主要是防止占位符多层嵌套 placeholder = parseStringValue(placeholder, placeholderResolver, visitedPlaceholders); // Now obtain the value for the fully resolved key... //根据key从环境变量中获取值。 String propVal = placeholderResolver.resolvePlaceholder(placeholder); if (propVal == null && this.valueSeparator != null) { int separatorIndex = placeholder.indexOf(this.valueSeparator); if (separatorIndex != -1) { String actualPlaceholder = placeholder.substring(0, separatorIndex); String defaultValue = placeholder.substring(separatorIndex + this.valueSeparator.length()); propVal = placeholderResolver.resolvePlaceholder(actualPlaceholder); if (propVal == null) { propVal = defaultValue; } } } if (propVal != null) { // Recursive invocation, parsing placeholders contained in the // previously resolved placeholder value. //这里防止获取到的值中包含占位符,又递归了一下 propVal = parseStringValue(propVal, placeholderResolver, visitedPlaceholders); //占位符替换 result.replace(startIndex, endIndex + this.placeholderSuffix.length(), propVal); if (logger.isTraceEnabled()) { logger.trace("Resolved placeholder '" + placeholder + "'"); } startIndex = result.indexOf(this.placeholderPrefix, startIndex + propVal.length()); } else if (this.ignoreUnresolvablePlaceholders) { // Proceed with unprocessed value. startIndex = result.indexOf(this.placeholderPrefix, endIndex + this.placeholderSuffix.length()); } else { throw new IllegalArgumentException("Could not resolve placeholder '" + placeholder + "'" + " in value \"" + value + "\""); } visitedPlaceholders.remove(originalPlaceholder); } else { startIndex = -1; } } //返回替换后的值 return result.toString(); }

我们再回到原来的方法。下面我们重点看一下refresh方法。

@Override	public void refresh() throws BeansException, IllegalStateException {	//防止"refresh"、"destroy"存在并发操作。		synchronized (this.startupShutdownMonitor) {			// 刷新前的准备工作,下面会讲			prepareRefresh();			// Tell the subclass to refresh the internal bean factory.			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();			// Prepare the bean factory for use in this context.			prepareBeanFactory(beanFactory);			try {				// Allows post-processing of the bean factory in context subclasses.				postProcessBeanFactory(beanFactory);				// Invoke factory processors registered as beans in the context.				invokeBeanFactoryPostProcessors(beanFactory);				// Register bean processors that intercept bean creation.				registerBeanPostProcessors(beanFactory);				// Initialize message source for this context.				initMessageSource();				// Initialize event multicaster for this context.				initApplicationEventMulticaster();				// Initialize other special beans in specific context subclasses.				onRefresh();				// Check for listener beans and register them.				registerListeners();				// Instantiate all remaining (non-lazy-init) singletons.				finishBeanFactoryInitialization(beanFactory);				// Last step: publish corresponding event.				finishRefresh();			}			catch (BeansException ex) {				if (logger.isWarnEnabled()) {					logger.warn("Exception encountered during context initialization - " +							"cancelling refresh attempt: " + ex);				}				// Destroy already created singletons to avoid dangling resources.				destroyBeans();				// Reset 'active' flag.				cancelRefresh(ex);				// Propagate exception to caller.				throw ex;			}			finally {				// Reset common introspection caches in Spring's core, since we				// might not ever need metadata for singleton beans anymore...				resetCommonCaches();			}		}	}

下面讲一下prepareRefresh,里面主要是设置了一下变量,做了一个校验,具体代码如下

protected void prepareRefresh() {	    //设置启动时间		this.startupDate = System.currentTimeMillis();		//设置启动变量		this.closed.set(false);		this.active.set(true);		if (logger.isInfoEnabled()) {			logger.info("Refreshing " + this);		}		// 钩子,给子类继承,实际没有用到		initPropertySources();		// 校验必配的环境变量有没有配置,下面会具体讲下		getEnvironment().validateRequiredProperties();		// Allow for the collection of early ApplicationEvents,		// to be published once the multicaster is available...		this.earlyApplicationEvents = new LinkedHashSet
(); }

校验环境变量有没有配置,这个方法很简单,就是遍历一下,然后判断值是否存在,不存在记录异常。

public void validateRequiredProperties() {		MissingRequiredPropertiesException ex = new MissingRequiredPropertiesException();		for (String key : this.requiredProperties) {			if (this.getProperty(key) == null) {				ex.addMissingRequiredProperty(key);			}		}		if (!ex.getMissingRequiredProperties().isEmpty()) {			throw ex;		}	}

我们再回到refresh方法,我们来看obtainFreshBeanFactory方法,这个方法是重点重点重点。

@Override	public void refresh() throws BeansException, IllegalStateException {	//防止"refresh"、"destroy"存在并发操作。		synchronized (this.startupShutdownMonitor) {			// 刷新前的准备工作,下面会讲			prepareRefresh();			// 解析bean,保存bean信息到注册中心(这里只是解析保存信息,没有生成bean实例)			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();			// Prepare the bean factory for use in this context.			prepareBeanFactory(beanFactory);			try {				// Allows post-processing of the bean factory in context subclasses.				postProcessBeanFactory(beanFactory);				// Invoke factory processors registered as beans in the context.				invokeBeanFactoryPostProcessors(beanFactory);				// Register bean processors that intercept bean creation.				registerBeanPostProcessors(beanFactory);				// Initialize message source for this context.				initMessageSource();				// Initialize event multicaster for this context.				initApplicationEventMulticaster();				// Initialize other special beans in specific context subclasses.				onRefresh();				// Check for listener beans and register them.				registerListeners();				// Instantiate all remaining (non-lazy-init) singletons.				finishBeanFactoryInitialization(beanFactory);				// Last step: publish corresponding event.				finishRefresh();			}			catch (BeansException ex) {				if (logger.isWarnEnabled()) {					logger.warn("Exception encountered during context initialization - " +							"cancelling refresh attempt: " + ex);				}				// Destroy already created singletons to avoid dangling resources.				destroyBeans();				// Reset 'active' flag.				cancelRefresh(ex);				// Propagate exception to caller.				throw ex;			}			finally {				// Reset common introspection caches in Spring's core, since we				// might not ever need metadata for singleton beans anymore...				resetCommonCaches();			}		}	}

我们来看下obtainFreshBeanFactory方法。

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {		//关闭旧的BeanFactory(如果有),创建新的BeanFactory,加载Bean定义,注册Bean等等		refreshBeanFactory();		//获取刚刚创建的BeanFactory		ConfigurableListableBeanFactory beanFactory = getBeanFactory();		if (logger.isDebugEnabled()) {			logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);		}		return beanFactory;	}

refreshBeanFactory方法

@Override	protected final void refreshBeanFactory() throws BeansException {		//如果ApplicationContext中已经加载过BeanFactory了,销毁所有Bean,关闭BeanFactory		//应用中BeanFactory本来就是可以多个的,这里不是说应用全局是否有BeanFactory,而是当前		//ApplicationContext是否有BeanFactory		if (hasBeanFactory()) {			destroyBeans();			closeBeanFactory();		}		try {			//初始化一个DefaultListableBeanFactory			DefaultListableBeanFactory beanFactory = createBeanFactory();			//用户BeanFactory的序列化			beanFactory.setSerializationId(getId());			//设置BeanFactory的两个配置属性;是否允许Bean覆盖,是否允许循环引用			customizeBeanFactory(beanFactory);			//加载Bean到BeanFactory中			loadBeanDefinitions(beanFactory);			synchronized (this.beanFactoryMonitor) {				this.beanFactory = beanFactory;			}		}		catch (IOException ex) {			throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);		}	}

我们当前是初始化,hasBeanFactory为false,这段代码先跳过。

我们看createBeanFactory方法,里面创建了个DefaultListableBeanFactory实例。
customizeBeanFactory里面设置了两个变量,Bean是否允许覆盖,刷新的时候使用;是否允许循环引用。这里启动的时候都是null,所有没有设置值。

protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {		if (this.allowBeanDefinitionOverriding != null) {			beanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);		}		if (this.allowCircularReferences != null) {			beanFactory.setAllowCircularReferences(this.allowCircularReferences);		}	}

重点方法是loadBeanDefinitions,里面是解析bean的过程。

@Override	protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {		// Create a new XmlBeanDefinitionReader for the given BeanFactory.		XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);		// Configure the bean definition reader with this context's		// resource loading environment.		beanDefinitionReader.setEnvironment(this.getEnvironment());		beanDefinitionReader.setResourceLoader(this);		beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));		// Allow a subclass to provide custom initialization of the reader,		// then proceed with actually loading the bean definitions.		initBeanDefinitionReader(beanDefinitionReader);		//重点		loadBeanDefinitions(beanDefinitionReader);	}

看一下loadBeanDefinitions方法,我们前端输入的的configLocations,所以走到reader.loadBeanDefinitions(configLocations)。

protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {		Resource[] configResources = getConfigResources();		if (configResources != null) {			reader.loadBeanDefinitions(configResources);		}		String[] configLocations = getConfigLocations();		if (configLocations != null) {		    //下面会讲			reader.loadBeanDefinitions(configLocations);		}	}

loadBeanDefinitions方法

public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException {		Assert.notNull(locations, "Location array must not be null");		int counter = 0;		for (String location : locations) {		    //下面会讲			counter += loadBeanDefinitions(location);		}		//返回总共加载的bean的数量		return counter;	}

loadBeanDefinitions方法最后调用了如下方法,actualResources为null

public int loadBeanDefinitions(String location, Set
actualResources) throws BeanDefinitionStoreException { //获取资源加载器 ResourceLoader resourceLoader = getResourceLoader(); if (resourceLoader == null) { throw new BeanDefinitionStoreException( "Cannot import bean definitions from location [" + location + "]: no ResourceLoader available"); } //前面有一段代码beanDefinitionReader.setResourceLoader(this);在AbstractXmlApplicationContext类中,继承了ResourcePatternResolver接口,由此可知,走的是if逻辑。 if (resourceLoader instanceof ResourcePatternResolver) { // Resource pattern matching available. try { //可以根据相对路径解析资源,这个里面主要是怎么根据路径找资源,不展开。 Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location); //具体的加载逻辑,下面会讲 int loadCount = loadBeanDefinitions(resources); if (actualResources != null) { for (Resource resource : resources) { actualResources.add(resource); } } if (logger.isDebugEnabled()) { logger.debug("Loaded " + loadCount + " bean definitions from location pattern [" + location + "]"); } return loadCount; } catch (IOException ex) { throw new BeanDefinitionStoreException( "Could not resolve bean definition resource pattern [" + location + "]", ex); } } else { // Can only load single resources by absolute URL. Resource resource = resourceLoader.getResource(location); int loadCount = loadBeanDefinitions(resource); if (actualResources != null) { actualResources.add(resource); } if (logger.isDebugEnabled()) { logger.debug("Loaded " + loadCount + " bean definitions from location [" + location + "]"); } return loadCount; } }

loadBeanDefinitions方法最后调用了loadBeanDefinitions(EncodedResource encodedResource)方法。

public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {		Assert.notNull(encodedResource, "EncodedResource must not be null");		if (logger.isInfoEnabled()) {			logger.info("Loading XML bean definitions from " + encodedResource.getResource());		}                //这里用了个线程本地变量,意义不明		Set
currentResources = this.resourcesCurrentlyBeingLoaded.get(); if (currentResources == null) { currentResources = new HashSet
(4); this.resourcesCurrentlyBeingLoaded.set(currentResources); } if (!currentResources.add(encodedResource)) { throw new BeanDefinitionStoreException( "Detected cyclic loading of " + encodedResource + " - check your import definitions!"); } try { InputStream inputStream = encodedResource.getResource().getInputStream(); try { InputSource inputSource = new InputSource(inputStream); if (encodedResource.getEncoding() != null) { inputSource.setEncoding(encodedResource.getEncoding()); } //重点 return doLoadBeanDefinitions(inputSource, encodedResource.getResource()); } finally { inputStream.close(); } } catch (IOException ex) { throw new BeanDefinitionStoreException( "IOException parsing XML document from " + encodedResource.getResource(), ex); } finally { currentResources.remove(encodedResource); if (currentResources.isEmpty()) { this.resourcesCurrentlyBeingLoaded.remove(); } } }

doLoadBeanDefinitions方法最后调用了DefaultBeanDefinitionDocumentReader的doRegisterBeanDefinitions方法

protected void doRegisterBeanDefinitions(Element root) {				BeanDefinitionParserDelegate parent = this.delegate;		this.delegate = createDelegate(getReaderContext(), root, parent);        //这里判断一下是不是spring原生的标签,如果是,判断profile是不是当前需要的,如果不是,直接返回。		if (this.delegate.isDefaultNamespace(root)) {			String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);			if (StringUtils.hasText(profileSpec)) {				String[] specifiedProfiles = StringUtils.tokenizeToStringArray(						profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);				if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {					if (logger.isInfoEnabled()) {						logger.info("Skipped XML bean definition file due to specified profiles [" + profileSpec +								"] not matching: " + getReaderContext().getResource());					}					return;				}			}		}        //钩子函数,解析前		preProcessXml(root);		//解析		parseBeanDefinitions(root, this.delegate);		//钩子函数,解析后		postProcessXml(root);		this.delegate = parent;	}

parseBeanDefinitions方法

protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {	    //这是spring默认的标签,比如beans		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);		}	}

parseDefaultElement方法

private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {	    //解析import节点		if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {			importBeanDefinitionResource(ele);		}		//解析alias节点		else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {			processAliasRegistration(ele);		}		//解析bean节点,重点		else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {			processBeanDefinition(ele, delegate);		}		//解析nested_beans节点		else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {			// recurse			doRegisterBeanDefinitions(ele);		}	}

processBeanDefinition方法

protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {	    //解析信息,放入BeanDefinitionHolder中		BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);		if (bdHolder != null) {			bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);			try {				// Register the final decorated instance.				BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());			}			catch (BeanDefinitionStoreException ex) {				getReaderContext().error("Failed to register bean definition with name '" +						bdHolder.getBeanName() + "'", ele, ex);			}			// Send registration event.			getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));		}	}

parseBeanDefinitionElement最后调用了如下方法。

public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, BeanDefinition containingBean) {	    //获取id		String id = ele.getAttribute(ID_ATTRIBUTE);		//获取name		String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);        //别名		List
aliases = new ArrayList
(); if (StringUtils.hasLength(nameAttr)) { String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS); aliases.addAll(Arrays.asList(nameArr)); } //如果没有设置id,则别名第一个作为beanName String beanName = id; if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) { beanName = aliases.remove(0); if (logger.isDebugEnabled()) { logger.debug("No XML 'id' specified - using '" + beanName + "' as bean name and " + aliases + " as aliases"); } } //校验名字是否重复 if (containingBean == null) { checkNameUniqueness(beanName, aliases, ele); } //解析节点,下面会讲 AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean); if (beanDefinition != null) { if (!StringUtils.hasText(beanName)) { try { if (containingBean != null) { beanName = BeanDefinitionReaderUtils.generateBeanName( beanDefinition, this.readerContext.getRegistry(), true); } else { beanName = this.readerContext.generateBeanName(beanDefinition); // Register an alias for the plain bean class name, if still possible, // if the generator returned the class name plus a suffix. // This is expected for Spring 1.2/2.0 backwards compatibility. String beanClassName = beanDefinition.getBeanClassName(); if (beanClassName != null && beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() && !this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) { aliases.add(beanClassName); } } if (logger.isDebugEnabled()) { logger.debug("Neither XML 'id' nor 'name' specified - " + "using generated bean name [" + beanName + "]"); } } catch (Exception ex) { error(ex.getMessage(), ele); return null; } } String[] aliasesArray = StringUtils.toStringArray(aliases); return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray); } return null; }

parseBeanDefinitionElement方法

public AbstractBeanDefinition parseBeanDefinitionElement(			Element ele, String beanName, BeanDefinition containingBean) {		this.parseState.push(new BeanEntry(beanName));        //获取类名		String className = null;		if (ele.hasAttribute(CLASS_ATTRIBUTE)) {			className = ele.getAttribute(CLASS_ATTRIBUTE).trim();		}        		try {		    //获取parent属性值,会继承parent的所有属性			String parent = null;			if (ele.hasAttribute(PARENT_ATTRIBUTE)) {				parent = ele.getAttribute(PARENT_ATTRIBUTE);			}			AbstractBeanDefinition bd = createBeanDefinition(className, parent);                        //解析attributes的键值对,下面会讲			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;		}		catch (ClassNotFoundException ex) {			error("Bean class [" + className + "] not found", ele, ex);		}		catch (NoClassDefFoundError err) {			error("Class that bean class [" + className + "] depends on not found", ele, err);		}		catch (Throwable ex) {			error("Unexpected failure during bean definition parsing", ele, ex);		}		finally {			this.parseState.pop();		}		return null;	}

到这里为止,bean的解析已经完成了。前面生成了一个BeanDefinition,但是还没有保存下来,保存动作实在registerBeanDefinition方法里面进行的

protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {		BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);		if (bdHolder != null) {			bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);			try {				// Register the final decorated instance.				//保存BeanDefinition到注册中心				BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());			}			catch (BeanDefinitionStoreException ex) {				getReaderContext().error("Failed to register bean definition with name '" +						bdHolder.getBeanName() + "'", ele, ex);			}			// Send registration event.			getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));		}	}

registerBeanDefinition方法

public static void registerBeanDefinition(			BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)			throws BeanDefinitionStoreException {		// 注册		String beanName = definitionHolder.getBeanName();		registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());		// 注册别名		String[] aliases = definitionHolder.getAliases();		if (aliases != null) {			for (String alias : aliases) {				registry.registerAlias(beanName, alias);			}		}	}

registerBeanDefinition方法

public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)			throws BeanDefinitionStoreException {		Assert.hasText(beanName, "Bean name must not be empty");		Assert.notNull(beanDefinition, "BeanDefinition must not be null");		if (beanDefinition instanceof AbstractBeanDefinition) {			try {				((AbstractBeanDefinition) beanDefinition).validate();			}			catch (BeanDefinitionValidationException ex) {				throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,						"Validation of bean definition failed", ex);			}		}		BeanDefinition oldBeanDefinition;        //获取老的定义		oldBeanDefinition = this.beanDefinitionMap.get(beanName);		if (oldBeanDefinition != null) {		    //不允许覆盖			if (!isAllowBeanDefinitionOverriding()) {				throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,						"Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName +						"': There is already [" + oldBeanDefinition + "] bound.");			}			else if (oldBeanDefinition.getRole() < beanDefinition.getRole()) {				// e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE				if (this.logger.isWarnEnabled()) {					this.logger.warn("Overriding user-defined bean definition for bean '" + beanName +							"' with a framework-generated bean definition: replacing [" +							oldBeanDefinition + "] with [" + beanDefinition + "]");				}			}			else if (!beanDefinition.equals(oldBeanDefinition)) {				if (this.logger.isInfoEnabled()) {					this.logger.info("Overriding bean definition for bean '" + beanName +							"' with a different definition: replacing [" + oldBeanDefinition +							"] with [" + beanDefinition + "]");				}			}			else {				if (this.logger.isDebugEnabled()) {					this.logger.debug("Overriding bean definition for bean '" + beanName +							"' with an equivalent definition: replacing [" + oldBeanDefinition +							"] with [" + beanDefinition + "]");				}			}			this.beanDefinitionMap.put(beanName, beanDefinition);		}		else {		    //如果bean已经在创建了,需要加锁			if (hasBeanCreationStarted()) {				// Cannot modify startup-time collection elements anymore (for stable iteration)				synchronized (this.beanDefinitionMap) {					this.beanDefinitionMap.put(beanName, beanDefinition);					List
updatedDefinitions = new ArrayList
(this.beanDefinitionNames.size() + 1); updatedDefinitions.addAll(this.beanDefinitionNames); updatedDefinitions.add(beanName); this.beanDefinitionNames = updatedDefinitions; if (this.manualSingletonNames.contains(beanName)) { Set
updatedSingletons = new LinkedHashSet
(this.manualSingletonNames); updatedSingletons.remove(beanName); this.manualSingletonNames = updatedSingletons; } } } else { // Still in startup registration phase //保存一下bean的定义 this.beanDefinitionMap.put(beanName, beanDefinition); this.beanDefinitionNames.add(beanName); this.manualSingletonNames.remove(beanName); } this.frozenBeanDefinitionNames = null; } if (oldBeanDefinition != null || containsSingleton(beanName)) { //重新设置beanDefinition,下面会继续讲 resetBeanDefinition(beanName); } }

resetBeanDefinition方法,删除合并的bean,删除单例,继承自这个类的也要特殊处理。

protected void resetBeanDefinition(String beanName) {		// Remove the merged bean definition for the given bean, if already created.		clearMergedBeanDefinition(beanName);		// Remove corresponding bean from singleton cache, if any. Shouldn't usually		// be necessary, rather just meant for overriding a context's default beans		// (e.g. the default StaticMessageSource in a StaticApplicationContext).		destroySingleton(beanName);		// Reset all bean definitions that have the given bean as parent (recursively).		for (String bdName : this.beanDefinitionNames) {			if (!beanName.equals(bdName)) {				BeanDefinition bd = this.beanDefinitionMap.get(bdName);				if (beanName.equals(bd.getParentName())) {					resetBeanDefinition(bdName);				}			}		}	}

到这里,我们总结一下,到这里为止,我们的bean已经解析完成了,信息保存在了beanDefinitionMap中,beanDefinitionNames中保存了已经解析的beanName。

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {				    //保存所有的BeanDefinition			private final Map
beanDefinitionMap = new ConcurrentHashMap
(256); //保存的beanName private volatile List
beanDefinitionNames = new ArrayList
(256); }

上文花了这么大的篇幅,我们只讲了一个ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();方法,我们继续看refresh方法。

@Override	public void refresh() throws BeansException, IllegalStateException {	//防止"refresh"、"destroy"存在并发操作。		synchronized (this.startupShutdownMonitor) {			// 刷新前的准备工作,下面会讲			prepareRefresh();			// 解析beanDefinition,注册beanDefinition.			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();			// 设置BeanFactory的类加载器,添加几个BeanPostProcessor,手动注册几个特殊的bean,下面重点讲这个方法。			prepareBeanFactory(beanFactory);			try {				// Allows post-processing of the bean factory in context subclasses.				postProcessBeanFactory(beanFactory);				// Invoke factory processors registered as beans in the context.				invokeBeanFactoryPostProcessors(beanFactory);				// Register bean processors that intercept bean creation.				registerBeanPostProcessors(beanFactory);				// Initialize message source for this context.				initMessageSource();				// Initialize event multicaster for this context.				initApplicationEventMulticaster();				// Initialize other special beans in specific context subclasses.				onRefresh();				// Check for listener beans and register them.				registerListeners();				// Instantiate all remaining (non-lazy-init) singletons.				finishBeanFactoryInitialization(beanFactory);				// Last step: publish corresponding event.				finishRefresh();			}			catch (BeansException ex) {				if (logger.isWarnEnabled()) {					logger.warn("Exception encountered during context initialization - " +							"cancelling refresh attempt: " + ex);				}				// Destroy already created singletons to avoid dangling resources.				destroyBeans();				// Reset 'active' flag.				cancelRefresh(ex);				// Propagate exception to caller.				throw ex;			}			finally {				// Reset common introspection caches in Spring's core, since we				// might not ever need metadata for singleton beans anymore...				resetCommonCaches();			}		}	}

prepareBeanFactory方法

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {		// Tell the internal bean factory to use the context's class loader etc.		//设置BeanFactory的类加载器,这里设置为加载当前ApplicationContext类的类加载器		beanFactory.setBeanClassLoader(getClassLoader());		beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));		beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));		//添加一个BeanPostProcessor,保存在beanPostProcessors中,这个processor		//实现了Aware接口的beans在初始化的时候,这个processor负责回调		//这个我们很常用,我们会为了获取applicationContext而implement ApplicationContextAware		//注意:它不仅仅回调ApplicationContextAware,还会负责回调EnvironmentAware,ResourceLoaderAware等。		//下面会重点讲一下。		beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));		//如果某个bean依赖于一下几个接口的实现类,在自动装配的时候忽略他们,spring会通过其他方式来处理这些依赖,保存在ignoredDependencyInterfaces的Set中		beanFactory.ignoreDependencyInterface(EnvironmentAware.class);		beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);		beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);		beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);		beanFactory.ignoreDependencyInterface(MessageSourceAware.class);		beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);		/**		 * 下面几行就是为特殊的几个bean赋值,如果有bean依赖了以下几个,会注入这边相应的值,目前保存在resolvableDependencies中		 * 之前我们说过,当前ApplicationContext持有一个BeanFactory,这里解释了第一行		 * ApplicationContext还继承了ResourceLoader、ApplicationEventPublisher、MessageSource		 * 所以对于这几个依赖,可以赋值为this,注意this是一个ApplicationContext		 * 这里没有MessageSource,MessageSource被注册成为了一个普通的bean		 */		beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);		beanFactory.registerResolvableDependency(ResourceLoader.class, this);		beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);		beanFactory.registerResolvableDependency(ApplicationContext.class, this);		//这个BeanPostProcessor也很简单,在bean实例化后,如果是ApplicationListener的子类,		//那么将其添加到listener列表中,可以理解为:注册事件监听器		beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));		//这里涉及到特殊的bean,名为:loadTimeWeaver,这不是我们的重点,忽略它		if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {			beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));			// Set a temporary ClassLoader for type matching.			beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));		}		/**		 * 从下面几行代码我们可以知道,Spring往往很“智能”就是因为它会帮我们默认注册一些有用的bean,		 * 放在singletonObjects中,并且往manualSingletonNames中添加一条记录,这是手动创建的bean		 */		// Register default environment beans.		if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {			beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());		}		if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {			beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());		}		if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {			beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());		}	}

总结一下,这里添加了两个特殊的BeanPostProcessor,添加了几个自动装配需要忽略的依赖,保存了factory的一些接口应用,手动注册了几个默认的bean。

然后看一下ApplicationContextAwareProcessor。这里主要对一些实现特殊接口的bean进行处理。

class ApplicationContextAwareProcessor implements BeanPostProcessor {	private final ConfigurableApplicationContext applicationContext;	private final StringValueResolver embeddedValueResolver;	/**	 * Create a new ApplicationContextAwareProcessor for the given context.	 */	public ApplicationContextAwareProcessor(ConfigurableApplicationContext applicationContext) {		this.applicationContext = applicationContext;		this.embeddedValueResolver = new EmbeddedValueResolver(applicationContext.getBeanFactory());	}    /**    *在初始化方法被调用之前执行    */	@Override	public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {		AccessControlContext acc = null;		if (System.getSecurityManager() != null &&				(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||						bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||						bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)) {			acc = this.applicationContext.getBeanFactory().getAccessControlContext();		}		if (acc != null) {			AccessController.doPrivileged(new PrivilegedAction() {				@Override				public Object run() {					invokeAwareInterfaces(bean);					return null;				}			}, acc);		}		else {		    //这里是重点			invokeAwareInterfaces(bean);		}		return bean;	}	private void invokeAwareInterfaces(Object bean) {	    //下面的一系列Aware都是为了把相关参数给用户定义的bean,如果实现了EnvironmentAware,我们就可以获取到Environment。		if (bean instanceof Aware) {			if (bean instanceof EnvironmentAware) {				((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());			}			if (bean instanceof EmbeddedValueResolverAware) {				((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);			}			if (bean instanceof ResourceLoaderAware) {				((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);			}			if (bean instanceof ApplicationEventPublisherAware) {				((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);			}			if (bean instanceof MessageSourceAware) {				((MessageSourceAware) bean).setMessageSource(this.applicationContext);			}			if (bean instanceof ApplicationContextAware) {				((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);			}		}	}    /**    *初始化方法执行之后啥都不做,直接返回原始的bean    */	@Override	public Object postProcessAfterInitialization(Object bean, String beanName) {		return bean;	}}

下面继续看refresh方法

@Override	public void refresh() throws BeansException, IllegalStateException {	//防止"refresh"、"destroy"存在并发操作。		synchronized (this.startupShutdownMonitor) {			// 刷新前的准备工作,下面会讲			prepareRefresh();			// 解析beanDefinition,注册beanDefinition.			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();			// 设置BeanFactory的类加载器,添加几个BeanPostProcessor,手动注册几个特殊的bean,下面重点讲这个方法。			prepareBeanFactory(beanFactory);			try {				// 这个方法是提供给子类实现的,可以在bean初始化前做一些特殊的处理,比如注册一些BeanPostProcessor				postProcessBeanFactory(beanFactory);				// 这个方法里面主要执行BeanFactoryPostProcessor的接口的bean的相关方法,下面重点讲这个				invokeBeanFactoryPostProcessors(beanFactory);				// Register bean processors that intercept bean creation.				registerBeanPostProcessors(beanFactory);				// Initialize message source for this context.				initMessageSource();				// Initialize event multicaster for this context.				initApplicationEventMulticaster();				// Initialize other special beans in specific context subclasses.				onRefresh();				// Check for listener beans and register them.				registerListeners();				// Instantiate all remaining (non-lazy-init) singletons.				finishBeanFactoryInitialization(beanFactory);				// Last step: publish corresponding event.				finishRefresh();			}			catch (BeansException ex) {				if (logger.isWarnEnabled()) {					logger.warn("Exception encountered during context initialization - " +							"cancelling refresh attempt: " + ex);				}				// Destroy already created singletons to avoid dangling resources.				destroyBeans();				// Reset 'active' flag.				cancelRefresh(ex);				// Propagate exception to caller.				throw ex;			}			finally {				// Reset common introspection caches in Spring's core, since we				// might not ever need metadata for singleton beans anymore...				resetCommonCaches();			}		}	}

invokeBeanFactoryPostProcessors方法

protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {	    //这是方法是重点,下面会主要讲		PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());		//这里是和切面相关的内容,先跳过		if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {			beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));			beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));		}	}

invokeBeanFactoryPostProcessors方法

public static void invokeBeanFactoryPostProcessors(            ConfigurableListableBeanFactory beanFactory, List
beanFactoryPostProcessors) { //进来的时候beanFactoryPostProcessors的size为0 // Invoke BeanDefinitionRegistryPostProcessors first, if any. Set
processedBeans = new HashSet
(); //DefaultListableBeanFactory继承了BeanDefinitionRegistry接口,所以这里会进入 if (beanFactory instanceof BeanDefinitionRegistry) { BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; //保存BeanFactoryPostProcessor List
regularPostProcessors = new LinkedList
(); //保存注册的BeanDefinitionRegistryPostProcessor List
registryProcessors = new LinkedList
(); //为0跳过 for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) { if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) { BeanDefinitionRegistryPostProcessor registryProcessor = (BeanDefinitionRegistryPostProcessor) postProcessor; registryProcessor.postProcessBeanDefinitionRegistry(registry); registryProcessors.add(registryProcessor); } else { regularPostProcessors.add(postProcessor); } } //保存当前注册的保存注册的BeanDefinitionRegistryPostProcessor,局部变量,用于多次复用 List
currentRegistryProcessors = new ArrayList
(); //-----------------------------------------------获取继承了PriorityOrdered的BeanDefinitionRegistryPostProcessor--------------------------------------------------------------- String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); for (String ppName : postProcessorNames) { if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); processedBeans.add(ppName); } } sortPostProcessors(currentRegistryProcessors, beanFactory); registryProcessors.addAll(currentRegistryProcessors); //这里调用postProcessBeanDefinitionRegistry方法 invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); currentRegistryProcessors.clear(); //----------------------------------------------获取继承了PriorityOrdered的BeanDefinitionRegistryPostProcessor结束------------------------------------------------- //-------------------------------------------获取继承了Ordered的BeanDefinitionRegistryPostProcessor------------------------------------------------------------------ postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); for (String ppName : postProcessorNames) { if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) { currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); processedBeans.add(ppName); } } sortPostProcessors(currentRegistryProcessors, beanFactory); registryProcessors.addAll(currentRegistryProcessors); //这里调用postProcessBeanDefinitionRegistry方法 invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); currentRegistryProcessors.clear(); //-------------------------------------------获取继承了Ordered的BeanDefinitionRegistryPostProcessor结束----------------------------------------------------------------- //-------------------------------------------获取继承了BeanDefinitionRegistryPostProcessor的其他------------------------------------------------------------------ // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear. boolean reiterate = true; while (reiterate) { reiterate = false; postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); for (String ppName : postProcessorNames) { if (!processedBeans.contains(ppName)) { currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); processedBeans.add(ppName); reiterate = true; } } sortPostProcessors(currentRegistryProcessors, beanFactory); registryProcessors.addAll(currentRegistryProcessors); invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); currentRegistryProcessors.clear(); } //-------------------------------------------获取继承了BeanDefinitionRegistryPostProcessor的其他结束------------------------------------------------------------------ //调用postProcessBeanFactory方法 invokeBeanFactoryPostProcessors(registryProcessors, beanFactory); //这里regularPostProcessors为空 invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory); } else { // Invoke factory processors registered with the context instance. invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory); } //-------------------------------------------------下面处理继承BeanFactoryPostProcessor的bean------------------------------------------------------------------------------ //获取继承BeanFactoryPostProcessor的bean String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false); // Separate between BeanFactoryPostProcessors that implement PriorityOrdered, // Ordered, and the rest. //继承priorityOrdered接口的 List
priorityOrderedPostProcessors = new ArrayList
(); //继承ordered接口的 List
orderedPostProcessorNames = new ArrayList
(); //没有继承排序接口的 List
nonOrderedPostProcessorNames = new ArrayList
(); for (String ppName : postProcessorNames) { if (processedBeans.contains(ppName)) { // skip - already processed in first phase above } else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class)); } else if (beanFactory.isTypeMatch(ppName, Ordered.class)) { orderedPostProcessorNames.add(ppName); } else { nonOrderedPostProcessorNames.add(ppName); } } //-----------------------------priorityOrdered处理------------------------------------------------- // 排序 sortPostProcessors(priorityOrderedPostProcessors, beanFactory); //执行postProcessBeanFactory方法 invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory); //----------------------------ordered处理--------------------------------------------------------- // 获取继承ordered接口的bean List
orderedPostProcessors = new ArrayList
(); for (String postProcessorName : orderedPostProcessorNames) { orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)); } //排序 sortPostProcessors(orderedPostProcessors, beanFactory); //执行postProcessBeanFactory方法 invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory); //--------------------------未继承排序接口的处理--------------------------------------------------- List
nonOrderedPostProcessors = new ArrayList
(); for (String postProcessorName : nonOrderedPostProcessorNames) { nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)); } //执行postProcessBeanFactory方法 invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory); //-------------------------------------------------处理继承BeanFactoryPostProcessor的bean结束------------------------------------------------------------------------------ // Clear cached merged bean definitions since the post-processors might have // modified the original metadata, e.g. replacing placeholders in values... beanFactory.clearMetadataCache(); }

执行逻辑自己看注释就可以了,这里主要说明一下BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessor两个接口的用法。

BeanFactoryPostProcessor接口主要用于修改BeanDefinition。下面是一个例子。

public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {        BeanDefinition beanDefinition = configurableListableBeanFactory.getBeanDefinition("helloService");        beanDefinition.getPropertyValues().add("sex", "女");    }}

BeanDefinitionRegistryPostProcessor接口主要用于新增或者删除一些BeanDefinition,当然他具备BeanFactoryPostProcessor接口的功能。下面是一个例子。

public class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {    /**     * 对注册的bean进行修改,可以删除和新增等     *     * @param beanDefinitionRegistry     * @throws BeansException     */    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {        RootBeanDefinition rootBeanDefinition = new RootBeanDefinition();        rootBeanDefinition.setBeanClass(ManualRegistryBean.class);        rootBeanDefinition.setScope(ConfigurableBeanFactory.SCOPE_SINGLETON);        beanDefinitionRegistry.registerBeanDefinition("manualRegistry", rootBeanDefinition);    }    /***     * 这个是BeanFactoryPostProcessor接口的方法,不做介绍     * @param configurableListableBeanFactory     * @throws BeansException     */    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {    }}

下面继续看refresh方法

@Override	public void refresh() throws BeansException, IllegalStateException {	//防止"refresh"、"destroy"存在并发操作。		synchronized (this.startupShutdownMonitor) {			// 刷新前的准备工作			prepareRefresh();			// 解析beanDefinition,注册beanDefinition.			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();			// 设置BeanFactory的类加载器,添加几个BeanPostProcessor,手动注册几个特殊的bean			prepareBeanFactory(beanFactory);			try {				// 这个方法是提供给子类实现的,可以在bean初始化前做一些特殊的处理,比如注册一些BeanPostProcessor				postProcessBeanFactory(beanFactory);				// 这个方法里面主要执行BeanFactoryPostProcessor的接口的bean的相关方法				invokeBeanFactoryPostProcessors(beanFactory);				// 注册继承了BeanPostProcessor接口的bean,下面重点讲这个				registerBeanPostProcessors(beanFactory);				// Initialize message source for this context.				initMessageSource();				// Initialize event multicaster for this context.				initApplicationEventMulticaster();				// Initialize other special beans in specific context subclasses.				onRefresh();				// Check for listener beans and register them.				registerListeners();				// Instantiate all remaining (non-lazy-init) singletons.				finishBeanFactoryInitialization(beanFactory);				// Last step: publish corresponding event.				finishRefresh();			}			catch (BeansException ex) {				if (logger.isWarnEnabled()) {					logger.warn("Exception encountered during context initialization - " +							"cancelling refresh attempt: " + ex);				}				// Destroy already created singletons to avoid dangling resources.				destroyBeans();				// Reset 'active' flag.				cancelRefresh(ex);				// Propagate exception to caller.				throw ex;			}			finally {				// Reset common introspection caches in Spring's core, since we				// might not ever need metadata for singleton beans anymore...				resetCommonCaches();			}		}	}

registerBeanPostProcessors方法

public static void registerBeanPostProcessors(            ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {        //获取继承了BeanPostProcessor的bean        String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);        // Register BeanPostProcessorChecker that logs an info message when        // a bean is created during BeanPostProcessor instantiation, i.e. when        // a bean is not eligible for getting processed by all BeanPostProcessors.        int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;        //这里又注册了一个BeanPostProcessor        beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));        // Separate between BeanPostProcessors that implement PriorityOrdered,        // Ordered, and the rest.        //继承自PriorityOrdered的        List
priorityOrderedPostProcessors = new ArrayList
(); //继承自MergedBeanDefinitionPostProcessor的 List
internalPostProcessors = new ArrayList
(); //继承自Ordered的 List
orderedPostProcessorNames = new ArrayList
(); //仅仅继承自BeanPostProcessor的 List
nonOrderedPostProcessorNames = new ArrayList
(); for (String ppName : postProcessorNames) { if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); priorityOrderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } else if (beanFactory.isTypeMatch(ppName, Ordered.class)) { orderedPostProcessorNames.add(ppName); } else { nonOrderedPostProcessorNames.add(ppName); } } //排序注册 sortPostProcessors(priorityOrderedPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors); // Next, register the BeanPostProcessors that implement Ordered. //获取继承自Ordered的 List
orderedPostProcessors = new ArrayList
(); for (String ppName : orderedPostProcessorNames) { BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); orderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } //排序注册 sortPostProcessors(orderedPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, orderedPostProcessors); // 获取仅仅继承自BeanPostProcessor的 List
nonOrderedPostProcessors = new ArrayList
(); for (String ppName : nonOrderedPostProcessorNames) { BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); nonOrderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } //注册 registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors); // 排序注册 sortPostProcessors(internalPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, internalPostProcessors); //这里注册了一个特殊的BeanPostProcessor beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext)); }

这里就是注册一下,没有实际执行。

下面继续看refresh方法

@Override	public void refresh() throws BeansException, IllegalStateException {	//防止"refresh"、"destroy"存在并发操作。		synchronized (this.startupShutdownMonitor) {			// 刷新前的准备工作			prepareRefresh();			// 解析beanDefinition,注册beanDefinition.			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();			// 设置BeanFactory的类加载器,添加几个BeanPostProcessor,手动注册几个特殊的bean			prepareBeanFactory(beanFactory);			try {				// 这个方法是提供给子类实现的,可以在bean初始化前做一些特殊的处理,比如注册一些BeanPostProcessor				postProcessBeanFactory(beanFactory);				// 这个方法里面主要执行BeanFactoryPostProcessor的接口的bean的相关方法				invokeBeanFactoryPostProcessors(beanFactory);				// 注册继承了BeanPostProcessor接口的bean				registerBeanPostProcessors(beanFactory);				// 这个是信息国际化,跳过				initMessageSource();				// 初始化当前ApplicationContext的事件广播器,先跳过				initApplicationEventMulticaster();				// 这个方法是提供给子类实现的,暂时没有用到				onRefresh();				// 注册事件监听器,监听器需要实现ApplicationListener接口。先跳过。				registerListeners();				// 这里初始化所有不是懒加载的单例bean,下面会重点讲				finishBeanFactoryInitialization(beanFactory);				// 完成刷新,也先跳过				finishRefresh();			}			catch (BeansException ex) {				if (logger.isWarnEnabled()) {					logger.warn("Exception encountered during context initialization - " +							"cancelling refresh attempt: " + ex);				}				// Destroy already created singletons to avoid dangling resources.				destroyBeans();				// Reset 'active' flag.				cancelRefresh(ex);				// Propagate exception to caller.				throw ex;			}			finally {				// Reset common introspection caches in Spring's core, since we				// might not ever need metadata for singleton beans anymore...				resetCommonCaches();			}		}	}

finishBeanFactoryInitialization方法

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(new StringValueResolver() {				@Override				public String resolveStringValue(String strVal) {					return getEnvironment().resolvePlaceholders(strVal);				}			});		}		//这是AspectJ相关的内容,先跳过		String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);		for (String weaverAwareName : weaverAwareNames) {			getBean(weaverAwareName);		}		// Stop using the temporary ClassLoader for type matching.		beanFactory.setTempClassLoader(null);		//spring开始预初始化singleton beans了,这个时候不能出现bean定义解析、加载、注册		beanFactory.freezeConfiguration();		//开始初始化,这是重点,下面讲		beanFactory.preInstantiateSingletons();	}

preInstantiateSingletons方法

@Override	public void preInstantiateSingletons() throws BeansException {		if (logger.isDebugEnabled()) {			logger.debug("Pre-instantiating singletons in " + this);		}		//this.beanDefinitionNames保存了所有的beanNames		List
beanNames = new ArrayList
(this.beanDefinitionNames); //触发所有的非懒加载的singleton beans的初始化操作 for (String beanName : beanNames) { //合并父Bean中的配置,注意
中的parent,下面会重点讲一下 RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName); //非抽象的、singleton,并且是非懒加载的,才会初始化 if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) { //处理FactoryBean if (isFactoryBean(beanName)) { //FactoryBean的话,在beanName前面加上'&'符号,再调用getBean final FactoryBean
factory = (FactoryBean
) getBean(FACTORY_BEAN_PREFIX + beanName); //判断当前FactoryBean是否是SmartFactoryBean的实现 boolean isEagerInit; if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) { isEagerInit = AccessController.doPrivileged(new PrivilegedAction
() { @Override public Boolean run() { return ((SmartFactoryBean
) factory).isEagerInit(); } }, getAccessControlContext()); } else { isEagerInit = (factory instanceof SmartFactoryBean && ((SmartFactoryBean
) factory).isEagerInit()); } if (isEagerInit) { getBean(beanName); } } else { //对于普通的Bean,只要调用getBean(beanName)这个方法就可以进行初始化了 getBean(beanName); } } } //到这里说明所有的singleton beans已经完成了初始化 //如果我们定义的bean是实现了SmartInitializingSingleton接口的,那么在这里得到回调 // Trigger post-initialization callback for all applicable beans... for (String beanName : beanNames) { Object singletonInstance = getSingleton(beanName); if (singletonInstance instanceof SmartInitializingSingleton) { final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance; if (System.getSecurityManager() != null) { AccessController.doPrivileged(new PrivilegedAction
() { @Override public Object run() { smartSingleton.afterSingletonsInstantiated(); return null; } }, getAccessControlContext()); } else { smartSingleton.afterSingletonsInstantiated(); } } } }

这里有几个概念,FactoryBean、SmartFactoryBean和SmartInitializingSingleton。这里分别先讲一下用法,方便理解。

先来讲一下FactoryBean,FactoryBean主要用于我们手动创建bean。用于一些复杂bean的创建。

//先定义一个beanpublic class Student {    private String sid;    private String name;    private String clazz;    private char sex;    public String getSid() {        return sid;    }    public void setSid(String sid) {        this.sid = sid;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getClazz() {        return clazz;    }    public void setClazz(String clazz) {        this.clazz = clazz;    }    public char getSex() {        return sex;    }    public void setSex(char sex) {        this.sex = sex;    }    @Override    public String toString() {        return "Student{" +                "sid='" + sid + '\'' +                ", name='" + name + '\'' +                ", clazz='" + clazz + '\'' +                ", sex=" + sex +                '}';    }}//创建bean的Factorypublic class StudentFactoryBean implements FactoryBean
{ private String studentInfo; //返回创建对象的方法 public Student getObject() throws Exception { Student student = new Student(); String[] infos = studentInfo.split(","); student.setSid(infos[0]); student.setName(infos[1]); student.setClazz(infos[2]); student.setSex(infos[3].charAt(0)); return student; } //创建的对象的类型 public Class
getObjectType() { return Student.class; } //是否单例 public boolean isSingleton() { return true; } public String getStudentInfo() { return studentInfo; } public void setStudentInfo(String studentInfo) { this.studentInfo = studentInfo; }}//配置
//使用public class Main { public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml"); Student student = applicationContext.getBean(Student.class); System.out.println(student); StudentFactoryBean studentFactoryBean = applicationContext.getBean(StudentFactoryBean.class); System.out.println(studentFactoryBean.getObjectType()); System.out.println(studentFactoryBean.getStudentInfo()); }}//输出Student{sid='04161000', name='张三', clazz='计科1901', sex=男}class com.mr.spring.factorybean.Student04161000,张三,计科1901,男

SmartFactoryBean主要在FactoryBean的基础上新增了isEagerInit接口

public interface SmartFactoryBean
extends FactoryBean
{ boolean isPrototype(); //是否初始化就生产bean boolean isEagerInit();}

SmartInitializingSingleton接口包含了一个方法afterSingletonsInstantiated,这个方法在所有单例初始化完成后执行

public class MySmartInitializingSingleton implements SmartInitializingSingleton {    public void afterSingletonsInstantiated() {        System.out.println("单例所有初始化完成执行。。。");    }}

在看下getMergedLocalBeanDefinition方法,这个方法主要是用来合并bean,下面先看个例子。

//测试类public class ParentBeanTest {    private String name;    private String sex;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getSex() {        return sex;    }    public void setSex(String sex) {        this.sex = sex;    }    @Override    public String toString() {        return "{" + name + "," + sex + "}";    }}//配置
//测试public class Main { public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml"); ParentBeanTest parentBeanTest = applicationContext.getBean(ParentBeanTest.class); System.out.println(parentBeanTest); }}//结果{占旭鹏,默认}

这里合并了父类的配置,主要是通过getMergedLocalBeanDefinition完成的,下面来看下具体的实现。

protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException {		// 看下有没有缓存,如果有,直接返回合并的结果		RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName);		if (mbd != null) {			return mbd;		}		//主要看这里		return getMergedBeanDefinition(beanName, getBeanDefinition(beanName));	}

getMergedBeanDefinition方法,主要自己看注释。

protected RootBeanDefinition getMergedBeanDefinition(			String beanName, BeanDefinition bd, BeanDefinition containingBd)			throws BeanDefinitionStoreException {		synchronized (this.mergedBeanDefinitions) {			RootBeanDefinition mbd = null;			// 这里再检查一遍,加锁检查,靠谱			if (containingBd == null) {				mbd = this.mergedBeanDefinitions.get(beanName);			}						//没有找到合并结果才继续,否则直接返回结果就可以了			if (mbd == null) {				//没有parent的情况下,返回当前bean定义的副本				if (bd.getParentName() == null) {					// Use copy of given root bean definition.					if (bd instanceof RootBeanDefinition) {						mbd = ((RootBeanDefinition) bd).cloneBeanDefinition();					}					else {						mbd = new RootBeanDefinition(bd);					}				}				else {					// Child bean definition: needs to be merged with parent.					BeanDefinition pbd;					try {						String parentBeanName = transformedBeanName(bd.getParentName());						if (!beanName.equals(parentBeanName)) {							//这里走了个递归,可能有多层							pbd = getMergedBeanDefinition(parentBeanName);						}						else {							//同名的情况下,使用父beanFactory的definition							BeanFactory parent = getParentBeanFactory();							if (parent instanceof ConfigurableBeanFactory) {								pbd = ((ConfigurableBeanFactory) parent).getMergedBeanDefinition(parentBeanName);							}							else {								throw new NoSuchBeanDefinitionException(parentBeanName,										"Parent name '" + parentBeanName + "' is equal to bean name '" + beanName +										"': cannot be resolved without an AbstractBeanFactory parent");							}						}					}					catch (NoSuchBeanDefinitionException ex) {						throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanName,								"Could not resolve parent bean definition '" + bd.getParentName() + "'", ex);					}										//获取父类的备份					mbd = new RootBeanDefinition(pbd);					//子类不是为空的属性去覆盖父类					mbd.overrideFrom(bd);				}				//设置默认作用域				if (!StringUtils.hasLength(mbd.getScope())) {					mbd.setScope(RootBeanDefinition.SCOPE_SINGLETON);				}				//containingBd为空,不考虑				if (containingBd != null && !containingBd.isSingleton() && mbd.isSingleton()) {					mbd.setScope(containingBd.getScope());				}				//保存合并结果				if (containingBd == null && isCacheBeanMetadata()) {					this.mergedBeanDefinitions.put(beanName, mbd);				}			}			return mbd;		}	}

下面主要看getBean方法,最后调用的方法如下

@SuppressWarnings("unchecked")	protected 
T doGetBean( final String name, final Class
requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException { /** * 我们在剖析初始化Bean的过程,但是getBean方法我们经常是用来从容器中获取Bean用的,注意切换思路, * 已经初始化过了就从容器中直接返回,否则就先初始化再返回,初始化的时候 * requiredType=null,args=null,typeCheckOnly=false */ //获取一个非别名的beanName,处理两种情况,一个是前面说的FactoryBean(前面带"&"), //一个是别名问题,因为这个方法是getBean,获取Bean用的,你要是传一个别名过来,是完全可以的。 final String beanName = transformedBeanName(name); Object bean; // Eagerly check singleton cache for manually registered singletons. //检查下是不是已经创建过了 Object sharedInstance = getSingleton(beanName); //这里说下args,虽然看上去一点不重要,前面我们一路进来的时候都是getBean(beanName), //所以args传参其实是null的 if (sharedInstance != null && args == null) { if (logger.isDebugEnabled()) { if (isSingletonCurrentlyInCreation(beanName)) { logger.debug("Returning eagerly cached instance of singleton bean '" + beanName + "' that is not fully initialized yet - a consequence of a circular reference"); } else { logger.debug("Returning cached instance of singleton bean '" + beanName + "'"); } } //如果是普通的Bean的话,直接返回sharedInstance, //如果是FactoryBean的话,返回它创建的那个实例对象 bean = getObjectForBeanInstance(sharedInstance, name, beanName, null); } else { if (isPrototypeCurrentlyInCreation(beanName)) { //创建过了此beanName的prototype类型的bean,那么抛异常, //往往是因为陷入了循环引用 throw new BeanCurrentlyInCreationException(beanName); } BeanFactory parentBeanFactory = getParentBeanFactory(); if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { //如果当前容器不存在这个BeanDefinition,试试父容器中有没有 String nameToLookup = originalBeanName(name); if (args != null) { //返回父容器的查询结果 // Delegation to parent with explicit args. return (T) parentBeanFactory.getBean(nameToLookup, args); } else { // No args -> delegate to standard getBean method. return parentBeanFactory.getBean(nameToLookup, requiredType); } } if (!typeCheckOnly) { //typeCheckOnly为false,将当前beanName放入一个alreadyCreated的Set集合中 markBeanAsCreated(beanName); } /** * 稍稍总结一下: * 到这里的话,要准备创建bean了,对于singleton的Bean来说,容器中还没创建过此Bean, * 对于prototype的Bean来说,本来就是要创建一个新的Bean */ try { final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); //校验是否是抽象的,抽象的不允许创建 checkMergedBeanDefinition(mbd, beanName, args); //先初始化依赖的所有Bean,注意,这里的依赖指的是depends-on中定义的依赖 String[] dependsOn = mbd.getDependsOn(); if (dependsOn != null) { for (String dep : dependsOn) { // 检查是不是有循环依赖,这里的依赖是depends-on,这个方法下面会重点讲一下。 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); } } } //如果是singleton scope的,创建singleton的实例 // Create bean instance. if (mbd.isSingleton()) { sharedInstance = getSingleton(beanName, new ObjectFactory
() { @Override public Object getObject() throws BeansException { try { // 执行创建Bean return createBean(beanName, mbd, args); } catch (BeansException ex) { // Explicitly remove instance from singleton cache: It might have been put there // eagerly by the creation process, to allow for circular reference resolution. // Also remove any beans that received a temporary reference to the bean. destroySingleton(beanName); throw ex; } } }); bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); } //如果是prototype,创建prototype的实例 else if (mbd.isPrototype()) { // It's a prototype -> create a new instance. Object prototypeInstance = null; try { beforePrototypeCreation(beanName); // 执行创建Bean prototypeInstance = createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName); } bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd); } //如果不是singleton和prototype的话,需要委托给相应的实现类来处理,先跳过 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, new ObjectFactory() { @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) { 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; } } // 最后,检查一下类型对不对,不对的话就抛异常,对的话就返回了 // Check if required type matches the type of the actual bean instance. if (requiredType != null && bean != null && !requiredType.isInstance(bean)) { try { return getTypeConverter().convertIfNecessary(bean, requiredType); } catch (TypeMismatchException ex) { if (logger.isDebugEnabled()) { logger.debug("Failed to convert bean '" + name + "' to required type '" + ClassUtils.getQualifiedName(requiredType) + "'", ex); } throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); } } return (T) bean; }

看一下isDependent方法,最终调用的方法如下

private boolean isDependent(String beanName, String dependentBeanName, Set
alreadySeen) { if (alreadySeen != null && alreadySeen.contains(beanName)) { return false; } //转换后的原名 String canonicalName = canonicalName(beanName); //获取依赖当前的所有bean Set
dependentBeans = this.dependentBeanMap.get(canonicalName); if (dependentBeans == null) { return false; } if (dependentBeans.contains(dependentBeanName)) { return true; } //这里主要考虑传递依赖的情况,A->B->C->A, //1.判断 这里先加载A,判断一下,发现map为空,继续往下 //2.注册 B被A依赖 B<-[A], //3.判断,这里去加载B,判断一下,发现C被B依赖了,取B的map发现B被A依赖,A没有被什么依赖,继续往下 //4.注册,C被B依赖 C<-[B], //5.判断,这里去加载C,判断一下,发现A被C依赖,取C的map发现C被B依赖,取B的map发现B被A依赖,循环依赖了 //= =老外反着来着,绕进去了 for (String transitiveDependency : dependentBeans) { if (alreadySeen == null) { alreadySeen = new HashSet
(); } alreadySeen.add(beanName); if (isDependent(transitiveDependency, dependentBeanName, alreadySeen)) { return true; } } return false; }

上面的方法只是判断,没有加载dependentBeanMap数据,下面的方法就是往dependentBeanMap中注册数据的。

public void registerDependentBean(String beanName, String dependentBeanName) {		String canonicalName = canonicalName(beanName);		synchronized (this.dependentBeanMap) {			Set
dependentBeans = this.dependentBeanMap.get(canonicalName); if (dependentBeans == null) { dependentBeans = new LinkedHashSet
(8); //beanName被dependentBeanName依赖 this.dependentBeanMap.put(canonicalName, dependentBeans); } dependentBeans.add(dependentBeanName); } synchronized (this.dependenciesForBeanMap) { Set
dependenciesForBean = this.dependenciesForBeanMap.get(dependentBeanName); if (dependenciesForBean == null) { dependenciesForBean = new LinkedHashSet
(8); //dependentBeanName依赖了beanName this.dependenciesForBeanMap.put(dependentBeanName, dependenciesForBean); } dependenciesForBean.add(canonicalName); } }

先看一下getSingleton方法,这里主要就是做了一下并发控制,然后创建实例保存了一下,具体的创建逻辑在singletonFactory中。

public Object getSingleton(String beanName, ObjectFactory
singletonFactory) { Assert.notNull(beanName, "'beanName' 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) { // Has the singleton object implicitly appeared in the meantime -> // if yes, proceed with it since the exception indicates that state. //如果发生异常考虑是并发的情况,重新获取一下实例,如果获取到就当创建成功。 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); } //如果是新创建的bean,这里需要保存一下实例 if (newSingleton) { addSingleton(beanName, singletonObject); } } return (singletonObject != NULL_OBJECT ? singletonObject : null); } }

这里主要看一下singletonFactory.getObject();的实现逻辑

protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {		if (logger.isDebugEnabled()) {			logger.debug("Creating instance of bean '" + beanName + "'");		}		RootBeanDefinition mbdToUse = mbd;		//确保BeanDefinition中的Class被加载,如果没有加载class,则用反射加载		Class
resolvedClass = resolveBeanClass(mbd, beanName); if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) { mbdToUse = new RootBeanDefinition(mbd); mbdToUse.setBeanClass(resolvedClass); } // Prepare method overrides. try { //准备方法覆盖,这里涉及一个概念:MethodOverrides,它来自于bean定义中的
//和
,先跳过 mbdToUse.prepareMethodOverrides(); } catch (BeanDefinitionValidationException ex) { throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(), beanName, "Validation of method overrides failed", ex); } try { //让BeanPostProcessors在这一步有机会返回代理,先跳过 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); } // 重头戏,创建bean Object beanInstance = doCreateBean(beanName, mbdToUse, args); if (logger.isDebugEnabled()) { logger.debug("Finished creating instance of bean '" + beanName + "'"); } return beanInstance; }

doCreateBean方法

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)			throws BeanCreationException {		// Instantiate the bean.		BeanWrapper instanceWrapper = null;		if (mbd.isSingleton()) {			instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);		}		if (instanceWrapper == null) {			//说明不是FactoryBean,这里实例化Bean,下面会讲			instanceWrapper = createBeanInstance(beanName, mbd, args);		}		//获取实例		final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);		//类型		Class
beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null); mbd.resolvedTargetType = beanType; //MergedBeanDefinitionPostProcessor,先跳过 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.isDebugEnabled()) { logger.debug("Eagerly caching bean '" + beanName + "' to allow for resolving potential circular references"); } addSingletonFactory(beanName, new ObjectFactory() { @Override public Object getObject() throws BeansException { return getEarlyBeanReference(beanName, mbd, bean); } }); } // Initialize the bean instance. Object exposedObject = bean; try { //这一步也是非常关键的,这一步负责属性装配,因为前面的实例只是实例化了,并没有设值,这里就是设值 populateBean(beanName, mbd, instanceWrapper); if (exposedObject != null) { //这里处理bean初始化完成后的各种调用,比如init-method方法,InitializingBean接口,BeanPostProcessor接口 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
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."); } } } } // Register bean as disposable.跳过 try { registerDisposableBeanIfNecessary(beanName, bean, mbd); } catch (BeanDefinitionValidationException ex) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex); } return exposedObject; }

createBeanInstance方法

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {		// Make sure bean class is actually resolved at this point.		//确保已经加载了此class,如果没有加载,则加载		Class
beanClass = resolveBeanClass(mbd, beanName); //校验一下这个类的访问权限 if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Bean class isn't public, and non-public access not allowed: " + beanClass.getName()); } if (mbd.getFactoryMethodName() != null) { //采用工厂方法实例化,先跳过,以后有时间补 return instantiateUsingFactoryMethod(beanName, mbd, args); } //如果不是第一次创建,比如第二次创建prototype bean //这种情况下,我们可以从第一次创建知道,采用无参构造方法,还是构造函数依赖注入,来完成实例化 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) { // 构造函数依赖注入,跳过,我们讲无参的 return autowireConstructor(beanName, mbd, null, null); } else { //无参构造函数,下面重点讲 return instantiateBean(beanName, mbd); } } // Candidate constructors for autowiring? //判断是否采用有参构造函数 Constructor
[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName); if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR || mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) { //构造函数依赖注入 return autowireConstructor(beanName, mbd, ctors, args); } // No special handling: simply use no-arg constructor. //调用无参构造函数 return instantiateBean(beanName, mbd); }

instantiateBean方法

protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {		try {			Object beanInstance;			final BeanFactory parent = this;			if (System.getSecurityManager() != null) {				beanInstance = AccessController.doPrivileged(new PrivilegedAction() {					@Override					public Object run() {						return getInstantiationStrategy().instantiate(mbd, beanName, parent);					}				}, getAccessControlContext());			}			else {				// 实例化				beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);			}			// 包装一下,返回			BeanWrapper bw = new BeanWrapperImpl(beanInstance);			initBeanWrapper(bw);			return bw;		}		catch (Throwable ex) {			throw new BeanCreationException(					mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);		}	}

instantiate方法

public Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner) {		// Don't override the class with CGLIB if no overrides.		//如果不存在方法覆写,那就使用java反射进行实例化,否则使用CGLIB,		//方法覆写,lookup-method和replaced-method		if (bd.getMethodOverrides().isEmpty()) {			Constructor
constructorToUse; synchronized (bd.constructorArgumentLock) { constructorToUse = (Constructor
) bd.resolvedConstructorOrFactoryMethod; if (constructorToUse == null) { final Class
clazz = bd.getBeanClass(); if (clazz.isInterface()) { throw new BeanInstantiationException(clazz, "Specified class is an interface"); } try { if (System.getSecurityManager() != null) { constructorToUse = AccessController.doPrivileged(new PrivilegedExceptionAction
>() { @Override public Constructor
run() throws Exception { return clazz.getDeclaredConstructor((Class[]) null); } }); } else { constructorToUse = clazz.getDeclaredConstructor((Class[]) null); } bd.resolvedConstructorOrFactoryMethod = constructorToUse; } catch (Throwable ex) { throw new BeanInstantiationException(clazz, "No default constructor found", ex); } } } //利用构造方法进行实例化 return BeanUtils.instantiateClass(constructorToUse); } else { // Must generate CGLIB subclass. //存在方法覆写,利用CGLIB来完成实例化,需要依赖于CGLIB生成子类 //tips:因为如果不使用CGLIB的话,存在override的情况JDK并没有提供相应的实话支持 return instantiateWithMethodInjection(bd, beanName, owner); } }

BeanUtils.instantiateClass方法,这里就是用反射创建了这个对象。下面会补一下用到的反射的知识,写个例子,不然会有点迷。

public static 
T instantiateClass(Constructor
ctor, Object... args) throws BeanInstantiationException { Assert.notNull(ctor, "Constructor must not be null"); try { ReflectionUtils.makeAccessible(ctor); return ctor.newInstance(args); } catch (InstantiationException ex) { throw new BeanInstantiationException(ctor, "Is it an abstract class?", ex); } catch (IllegalAccessException ex) { throw new BeanInstantiationException(ctor, "Is the constructor accessible?", ex); } catch (IllegalArgumentException ex) { throw new BeanInstantiationException(ctor, "Illegal arguments for constructor", ex); } catch (InvocationTargetException ex) { throw new BeanInstantiationException(ctor, "Constructor threw exception", ex.getTargetException()); } }

在看这个方法populateBean,这个方法用于设置属性。

protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {		// bean实例的所有属性都在这里		PropertyValues pvs = mbd.getPropertyValues();		if (bw == null) {			if (!pvs.isEmpty()) {				throw new BeanCreationException(						mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");			}			else {				// Skip property population phase for null instance.				return;			}		}		//到这步的时候,bean实例化完成(通过工厂方法或构造方法),但是还没开始属性设值,		//InstantiationAwareBeanPostProcessor的实现类可以在这里对bean进行状态修改,		boolean continueWithPropertyPopulation = true;		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {			for (BeanPostProcessor bp : getBeanPostProcessors()) {				if (bp instanceof InstantiationAwareBeanPostProcessor) {					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;					//如果返回false,代表不需要进行后续的属性设值,也不需要再经过其他的BeanPostProcessor的处理					if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {						continueWithPropertyPopulation = false;						break;					}				}			}		}		if (!continueWithPropertyPopulation) {			return;		}		if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||				mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {			MutablePropertyValues newPvs = new MutablePropertyValues(pvs);			// Add property values based on autowire by name if applicable.			//通过名字找到所有属性值,如果是bean依赖,先初始化依赖的bean,记录依赖关系			if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {				autowireByName(beanName, mbd, bw, newPvs);			}			//通过类型装配			// Add property values based on autowire by type if applicable.			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;						//这里有个非常有用的BeanPostProcessor:AutowiredAnnotationBeanPostProcessor						//对采用@Autowired、@Value注解的依赖进行设值						pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);						if (pvs == null) {							return;						}					}				}			}			if (needsDepCheck) {				checkDependencies(beanName, mbd, filteredPds, pvs);			}		}		//设值bean实例的属性值		applyPropertyValues(beanName, mbd, bw, pvs);	}

autowireByName方法,这里主要是bean的注入(还没有注入,保存了一下引用,这样pvs中就包含了所有值)

protected void autowireByName(			String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {		String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);		for (String propertyName : propertyNames) {			//如果包含的是一个bean			if (containsBean(propertyName)) {				Object bean = getBean(propertyName);				//获取bean,保存一下引用,新增依赖关系				pvs.add(propertyName, bean);				registerDependentBean(propertyName, beanName);				if (logger.isDebugEnabled()) {					logger.debug("Added autowiring by name from bean name '" + beanName +							"' via property '" + propertyName + "' to bean named '" + propertyName + "'");				}			}			else {				if (logger.isTraceEnabled()) {					logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName +							"' by name: no matching bean found");				}			}		}	}

applyPropertyValues方法,用于设置属性值。

protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {		if (pvs == null || pvs.isEmpty()) {			return;		}		if (System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) {			((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());		}		MutablePropertyValues mpvs = null;		List
original; //进入这里 if (pvs instanceof MutablePropertyValues) { mpvs = (MutablePropertyValues) pvs; if (mpvs.isConverted()) { // Shortcut: use the pre-converted values as-is. try { bw.setPropertyValues(mpvs); return; } catch (BeansException ex) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Error setting property values", ex); } } 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); // Create a deep copy, resolving any references for values. List
deepCopy = new ArrayList
(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); } // Possibly store converted value in merged bean definition, // in order to avoid re-conversion for every created bean instance. 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(); } // Set our (possibly massaged) deep copy. try { bw.setPropertyValues(new MutablePropertyValues(deepCopy)); } catch (BeansException ex) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Error setting property values", ex); } }

initializeBean方法,里面主要完成一些接口方法的调用。

protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {		if (System.getSecurityManager() != null) {			AccessController.doPrivileged(new PrivilegedAction() {				@Override				public Object run() {					invokeAwareMethods(beanName, bean);					return null;				}			}, getAccessControlContext());		}		else {			//特定接口值的设定			invokeAwareMethods(beanName, bean);		}		Object wrappedBean = bean;		if (mbd == null || !mbd.isSynthetic()) {			//BeanPostProcessor的postProcessBeforeInitialization回调			wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);		}		try {			//afterPropertiesSet方法调用和init方法调用			invokeInitMethods(beanName, wrappedBean, mbd);		}		catch (Throwable ex) {			throw new BeanCreationException(					(mbd != null ? mbd.getResourceDescription() : null),					beanName, "Invocation of init method failed", ex);		}		if (mbd == null || !mbd.isSynthetic()) {			//postProcessAfterInitialization方法调用			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);		}		return wrappedBean;	}

下面继续看refresh方法,到此已经刷新完毕了。

@Override	public void refresh() throws BeansException, IllegalStateException {	//防止"refresh"、"destroy"存在并发操作。		synchronized (this.startupShutdownMonitor) {			// 刷新前的准备工作			prepareRefresh();			// 解析beanDefinition,注册beanDefinition.			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();			// 设置BeanFactory的类加载器,添加几个BeanPostProcessor,手动注册几个特殊的bean			prepareBeanFactory(beanFactory);			try {				// 这个方法是提供给子类实现的,可以在bean初始化前做一些特殊的处理,比如注册一些BeanPostProcessor				postProcessBeanFactory(beanFactory);				// 这个方法里面主要执行BeanFactoryPostProcessor的接口的bean的相关方法				invokeBeanFactoryPostProcessors(beanFactory);				// 注册继承了BeanPostProcessor接口的bean				registerBeanPostProcessors(beanFactory);				// 这个是信息国际化,跳过				initMessageSource();				// 初始化当前ApplicationContext的事件广播器,先跳过				initApplicationEventMulticaster();				// 这个方法是提供给子类实现的,暂时没有用到				onRefresh();				// 注册事件监听器,监听器需要实现ApplicationListener接口。先跳过。				registerListeners();				// 这里初始化所有不是懒加载的单例bean。				finishBeanFactoryInitialization(beanFactory);				// 完成刷新				finishRefresh();			}			catch (BeansException ex) {				if (logger.isWarnEnabled()) {					logger.warn("Exception encountered during context initialization - " +							"cancelling refresh attempt: " + ex);				}				// Destroy already created singletons to avoid dangling resources.				destroyBeans();				// Reset 'active' flag.				cancelRefresh(ex);				// Propagate exception to caller.				throw ex;			}			finally {				// Reset common introspection caches in Spring's core, since we				// might not ever need metadata for singleton beans anymore...				resetCommonCaches();			}		}	}

= = 结束,中间有些细节有空再补充。

转载地址:http://psjqi.baihongyu.com/

你可能感兴趣的文章
Android上C++对象的自动回收机制分析
查看>>
从spin_lock到spin_lock_irqsave
查看>>
sdio 驱动
查看>>
T-SQL中的聚合函数中的SUM()函数与AVG函数()
查看>>
T-SQL中的聚合函数(二)
查看>>
分组查询
查看>>
2021-06-04
查看>>
最长无重复子数组
查看>>
Dual-Primal Graph Convolutional Networks 对偶-原始图卷积神经网络
查看>>
GoGNN: Graph of Graphs Neural Network for Predicting Structured Entity Interactions
查看>>
Estimating Node Importance in Knowledge Graphs Using Graph Neural Networks
查看>>
DiffPool: Hierarchical Graph Representation Learning with Differentiable Pooling
查看>>
MuchGCN:Multi-Channel Graph Convolutional Networks
查看>>
kernel_size为1的卷积核与全连接层的关系
查看>>
STRATEGIES FOR PRE-TRAINING GRAPH NEURAL NETWORKS
查看>>
PAT_A 1010. Radix (25)
查看>>
PAT_A 1005. Spell It Right (20)
查看>>
PAT_A 1012. The Best Rank (25)
查看>>
PAT_A 1013. Battle Over Cities (25)
查看>>
PAT_A 1015. Reversible Primes (20)
查看>>