Spring解析xml并注册
Spring 有两大特性IOC 和 AOP
在两者的基础之上,Spring还需要解析xml配置文件,注册bean才能实现完整的IOC和AOP
Spring是如何解析xml和注册的呢
我分为几个阶段
1.资源路径(***.xml)定位
2.解析资源,并封装到beanDefinition中
3.将beanDefinition添加到BeanFactory
4.这个时候就可以通过BeanFactory 去创建对象
直接从源码开始学习.
package it.luke.aop;
import it.luke.dao.UserDao;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.lang.reflect.Proxy;
public class Main {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserDao userDao = (UserDao)context.getBean("userDao");
userDao.query();
System.out.println(userDao.getName());
}
}
ClassPathXmlApplicationContext来作为入口,走读代码
public ClassPathXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException {
super(parent);
//进行配置的设置
//setConfigLocations(configLocations);通过set,将配置资源路径添加到资源容器中
setConfigLocations(configLocations);
if (refresh) {
主要逻辑,解析配置,监听等等...
refresh();
}
}
public abstract class AbstractRefreshableConfigApplicationContext extends AbstractRefreshableApplicationContext
implements BeanNameAware, InitializingBean {
public void setConfigLocations(@Nullable 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;
}
}
}
将我们的配置文件的路径添加到我们的环境之后,主要逻辑都在refresh()这个方法之中
/**
* refresh()
* 构建BeanFactory,以便于产生所需的 Bean。
* 注册可能感兴趣的事件。
* 常见Bean实例对象。
* 触发被监听的事件。
* @throws BeansException
* @throws IllegalStateException
*/
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
//
//主要基于这个方法,进行的解析等操作
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
....//(依赖注入的内容待补充)
}
前面已经将资源路径添加到环境里面了,这里通过obtainFreshBeanFactory()这个方法,开始进行构造
public abstract class AbstractApplicationContext extends DefaultResourceLoader
implements ConfigurableApplicationContext {
...
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
//更新Bean工厂(子抽象类实现)
refreshBeanFactory();
return getBeanFactory();
}
...
}
Spring这里采用了很多抽象类进行分工,不同的抽象级别,实现不同的方法,(绕晕了几次…)
public abstract class AbstractRefreshableApplicationContext extends AbstractApplicationContext {
....
protected final void refreshBeanFactory() throws BeansException {
if (hasBeanFactory()) {
// 如果存在就销毁
destroyBeans();
closeBeanFactory();
}
try {
//创建一个beanFactory
DefaultListableBeanFactory beanFactory = createBeanFactory();
// 设置序列化
beanFactory.setSerializationId(getId());
// 定制的BeanFactory
customizeBeanFactory(beanFactory);
//使用BeanFactory加载bean定义 AbstractXmlApplicationContext
loadBeanDefinitions(beanFactory);
synchronized (this.beanFactoryMonitor) {
this.beanFactory = beanFactory;
}
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}
....
}
这里创建了一个beanFactory以及对他进行配置等,是为了后面使用的,现在主要是通过loadBeanDefinitions(beanFactory);这个方法将我们的工厂类完善,这个方法也是子类实现的
public abstract class AbstractXmlApplicationContext extends AbstractRefreshableConfigApplicationContext {
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
// Create a new XmlBeanDefinitionReader for the given BeanFactory.
//初始化一个beanDefinitionReader
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);
}
}
这里XmlBeanDefinitionReader(beanFactory),这里的方法名可以看出,这是在为了解析xml做准备,所以看一下他里面的逻辑
protected AbstractBeanDefinitionReader(BeanDefinitionRegistry registry) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
this.registry = registry;
// Determine ResourceLoader to use.
if (this.registry instanceof ResourceLoader) {
this.resourceLoader = (ResourceLoader) this.registry;
}
else {
//初始化一个有当前类加载器的ResourceLoader
this.resourceLoader = new PathMatchingResourcePatternResolver();
}
// Inherit Environment if possible
if (this.registry instanceof EnvironmentCapable) {
this.environment = ((EnvironmentCapable) this.registry).getEnvironment();
}
else {
//初始化环境
this.environment = new StandardEnvironment();
}
}
可以看到它初始化了当前的资源加载器,(为了加载到我们的xml)由于我们的传入的资源路径是相对路径,所以这里采用了通过类加载器来调用资源加载器的形式来调用我们的资源路径.
看会上一份源码,其中更重要的是loadBeanDefinitions(beanDefinitionReader);这个方法
public abstract class AbstractXmlApplicationContext extends AbstractRefreshableConfigApplicationContext {
....
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
Resource[] configResources = getConfigResources();
if (configResources != null) {
reader.loadBeanDefinitions(configResources);
}
String[] configLocations = getConfigLocations();
if (configLocations != null) {
//configLocations 是前面载入到容器中的xml路径
reader.loadBeanDefinitions(configLocations);
}
}
.....
}
public abstract class AbstractBeanDefinitionReader implements BeanDefinitionReader, EnvironmentCapable {
.....
@Override
public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException {
Assert.notNull(locations, "Location array must not be null");
int count = 0;
for (String location : locations) {
count += loadBeanDefinitions(location);
}
return count;
}
}
loadBeanDefinitions(location) 此处的location是前面存入的资源路径
public int loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources) throws BeanDefinitionStoreException {
ResourceLoader resourceLoader = getResourceLoader();
if (resourceLoader == null) {
throw new BeanDefinitionStoreException(
"Cannot load bean definitions from location [" + location + "]: no ResourceLoader available");
}
if (resourceLoader instanceof ResourcePatternResolver) {
// Resource pattern matching available.
try {
//获取指定资源
Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
//主要的解析逻辑---->
int count = loadBeanDefinitions(resources);
if (actualResources != null) {
Collections.addAll(actualResources, resources);
}
if (logger.isTraceEnabled()) {
logger.trace("Loaded " + count + " bean definitions from location pattern [" + location + "]");
}
return count;
}
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 count = loadBeanDefinitions(resource);
if (actualResources != null) {
actualResources.add(resource);
}
if (logger.isTraceEnabled()) {
logger.trace("Loaded " + count + " bean definitions from location [" + location + "]");
}
return count;
}
}
@Override
public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException {
Assert.notNull(resources, "Resource array must not be null");
int count = 0;
for (Resource resource : resources) {
资源解析--->子类实现
count += loadBeanDefinitions(resource);
}
return count;
}
这里通过调用loadBeanDefinitions()这个方法,将资源传入,
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
Assert.notNull(encodedResource, "EncodedResource must not be null");
if (logger.isTraceEnabled()) {
logger.trace("Loading XML bean definitions from " + encodedResource);
}
Set<EncodedResource> 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();
}
}
}
这里可以看到,通过传入的encodedResource->获取到输入流->doLoadBeanDefinitions(inputSource, encodedResource.getResource());
将xml配置转化成输入流传入下个逻辑处理
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
throws BeanDefinitionStoreException {
try {
//将输入流解析成doc对象(解析xml)
Document doc = doLoadDocument(inputSource, resource);
//通过带有xml信息的doc对象和resource 进行注册
int count = registerBeanDefinitions(doc, resource);
if (logger.isDebugEnabled()) {
logger.debug("Loaded " + count + " bean definitions from " + resource);
}
return count;
}
catch (BeanDefinitionStoreException ex) {
throw ex;
}
catch (SAXParseException ex) {
throw new XmlBeanDefinitionStoreException(resource.getDescription(),
"Line " + ex.getLineNumber() + " in XML document from " + resource + " is invalid", ex);
}
catch (SAXException ex) {
throw new XmlBeanDefinitionStoreException(resource.getDescription(),
"XML document from " + resource + " is invalid", ex);
}
catch (ParserConfigurationException ex) {
throw new BeanDefinitionStoreException(resource.getDescription(),
"Parser configuration exception parsing XML from " + resource, ex);
}
catch (IOException ex) {
throw new BeanDefinitionStoreException(resource.getDescription(),
"IOException parsing XML document from " + resource, ex);
}
catch (Throwable ex) {
throw new BeanDefinitionStoreException(resource.getDescription(),
"Unexpected exception parsing XML document from " + resource, ex);
}
}
这里主要是两个方法,
doLoadDocument(inputSource, resource) ->将xml输入流解析成一个doc对象
registerBeanDefinitions(doc, resource);->通过解析doc,进行bean的初步构建
public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
int countBefore = getRegistry().getBeanDefinitionCount();
//该方法最后从文档对象总获取根元素 --子类实现
documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
return getRegistry().getBeanDefinitionCount() - countBefore;
}
@Override
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
this.readerContext = readerContext;
//doc.getDocumentElement() 获取到xml中的root节点 -- >Element root
doRegisterBeanDefinitions(doc.getDocumentElement());
}
到这里,我们解析的doc,通过getDocumentElement()获取根节点也就是beans…
//注册
protected void doRegisterBeanDefinitions(Element root) {
// Any nested <beans> elements will cause recursion in this method. In
// order to propagate and preserve <beans> default-* attributes correctly,
// keep track of the current (parent) delegate, which may be null. Create
// the new (child) delegate with a reference to the parent for fallback purposes,
// then ultimately reset this.delegate back to its original (parent) reference.
// this behavior emulates a stack of delegates without actually necessitating one.
BeanDefinitionParserDelegate parent = this.delegate;
this.delegate = createDelegate(getReaderContext(), root, parent);
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);
// We cannot use Profiles.of(...) since profile expressions are not supported
// in XML config. See SPR-12458 for details.
if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
if (logger.isDebugEnabled()) {
logger.debug("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) {
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
Element ele = (Element) node;
if (delegate.isDefaultNamespace(ele)) {
//进行匹配,根据节点的不一样,进行不同的解析(import,alias,bean,beans)
parseDefaultElement(ele, delegate);
}
else {
delegate.parseCustomElement(ele);
}
}
}
}
else {
delegate.parseCustomElement(root);
}
}
从这里开始,进行遍历解析我们主节点下面的那些子节点的类型,不同的子节点,有不同的解析模式parseDefaultElement(…)…
private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
//节点类型匹配
if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
importBeanDefinitionResource(ele);
}
else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
processAliasRegistration(ele);
}
//解析bean(主要)
else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
processBeanDefinition(ele, delegate);
}
else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
// recurse
doRegisterBeanDefinitions(ele);
}
}
这里主要看bean的解析方法
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
//创建一个持有者 解析class类 并持有他BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
if (bdHolder != null) {
bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
try {
// Register the final decorated instance.
//执行完后getReaderContext()中就已经注册了beanDefiniition
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));
}
}
这里做了两个操作,
一个 是将解析出来的节点元素信息封装成一个beanDefinition —>parseBeanDefinitionElement(…)
一个是将解析封装的beanDefinition进行注册 ->registerBeanDefinition(…)
先看解析封装
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, @Nullable BeanDefinition containingBean) {
//解析id属性ID_ATTRIBUTE ->id
String id = ele.getAttribute(ID_ATTRIBUTE);
//解析name属性NAME_ATTRIBUTE ->name
String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);
List<String> aliases = new ArrayList<>();
if (StringUtils.hasLength(nameAttr)) {
String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS);
aliases.addAll(Arrays.asList(nameArr));
}
//获取id
String beanName = id;
if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) {
beanName = aliases.remove(0);
if (logger.isTraceEnabled()) {
logger.trace("No XML 'id' specified - using '" + beanName +
"' as bean name and " + aliases + " as aliases");
}
}
if (containingBean == null) {
//检查id是否唯一(待)
checkNameUniqueness(beanName, aliases, ele);
}
//解析节点下的信息 解析出来成员变量,....用来初始化beanDefinition containingBean -> null
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.isTraceEnabled()) {
logger.trace("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);
//包含名称和别名的bean定义的Holder。可以注册为内部bean的占位符。
return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
}
return null;
}
这个方法主要通过parseBeanDefinitionElement()来生产一个beanDefinition (这个就是我们要的)
所以我们看一下这个方法
@Nullable
public AbstractBeanDefinition parseBeanDefinitionElement(
Element ele, String beanName, @Nullable BeanDefinition containingBean) {
//beanName-> id
//ele当前解析的子节点ele
this.parseState.push(new BeanEntry(beanName));
String className = null;
//CLASS_ATTRIBUTE -> class 获取标签属性class 获得全路径类名
if (ele.hasAttribute(CLASS_ATTRIBUTE)) {
className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
}
String parent = null;
if (ele.hasAttribute(PARENT_ATTRIBUTE)) {
//PARENT_ATTRIBUTE -> parent
parent = ele.getAttribute(PARENT_ATTRIBUTE);
}
try {
//根据提供的全路径类名和parent 初始化一个beanDefinition
AbstractBeanDefinition bd = createBeanDefinition(className, parent);
//将给定bean元素的属性应用于给定bean的定义。(判断是否抽象,单例...)
parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));
//解析给定元素(如果有的话)下面的元元素
parseMetaElements(ele, bd);
//解析查找-覆盖给定bean元素的子元素。
parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
//解析给定bean元素的替换方法子元素。
parseReplacedMethodSubElements(ele, bd.getMethodOverrides());
//解析给定bean元素的构造函数-参数子元素。
parseConstructorArgElements(ele, bd);
//解析给定bean元素的属性子元素。(成员变量)
parsePropertyElements(ele, bd);
//解析给定bean元素的限定符子元素。
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;
}
解析后的创建的BeanDefinition带有id和全路径类名,然后通过封装成BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);进行返回
然后我们来看注册,前面的代码中的
BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
public static void registerBeanDefinition(
BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
throws BeanDefinitionStoreException {
// Register bean definition under primary name.
//获取bean的id
String beanName = definitionHolder.getBeanName();
//将BeanDefinition()根据beanName 注册起来 -->子类实现
registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());
// Register aliases for bean name, if any.
String[] aliases = definitionHolder.getAliases();
if (aliases != null) {
for (String alias : aliases) {
registry.registerAlias(beanName, alias);
}
}
}
/**
*
* @param beanName bean的id
* @param beanDefinition 前面构建初始化的beanDefinition
* @throws BeanDefinitionStoreException
*/
@Override
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 existingDefinition = this.beanDefinitionMap.get(beanName);
//判断是否已经有同个beanName的对象
if (existingDefinition != null) {
if (!isAllowBeanDefinitionOverriding()) {
throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
}
else if (existingDefinition.getRole() < beanDefinition.getRole()) {
// e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
if (logger.isInfoEnabled()) {
logger.info("Overriding user-defined bean definition for bean '" + beanName +
"' with a framework-generated bean definition: replacing [" +
existingDefinition + "] with [" + beanDefinition + "]");
}
}
else if (!beanDefinition.equals(existingDefinition)) {
if (logger.isDebugEnabled()) {
logger.debug("Overriding bean definition for bean '" + beanName +
"' with a different definition: replacing [" + existingDefinition +
"] with [" + beanDefinition + "]");
}
}
else {
if (logger.isTraceEnabled()) {
logger.trace("Overriding bean definition for bean '" + beanName +
"' with an equivalent definition: replacing [" + existingDefinition +
"] with [" + beanDefinition + "]");
}
}
this.beanDefinitionMap.put(beanName, beanDefinition);
}
//bean还没注册
else {
if (hasBeanCreationStarted()) {
// Cannot modify startup-time collection elements anymore (for stable iteration)
synchronized (this.beanDefinitionMap) {
//将beanName, beanDefinition 放入map中
this.beanDefinitionMap.put(beanName, beanDefinition);
List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
updatedDefinitions.addAll(this.beanDefinitionNames);
updatedDefinitions.add(beanName);
this.beanDefinitionNames = updatedDefinitions;
removeManualSingletonName(beanName);
}
}
else {
// Still in startup registration phase
this.beanDefinitionMap.put(beanName, beanDefinition);
this.beanDefinitionNames.add(beanName);
removeManualSingletonName(beanName);
}
this.frozenBeanDefinitionNames = null;
}
if (existingDefinition != null || containsSingleton(beanName)) {
resetBeanDefinition(beanName);
}
else if (isConfigurationFrozen()) {
clearByTypeCache();
}
}
这里通过this.beanDefinitionMap.put(beanName, beanDefinition);
将id和对应的beanDefinition存放到map中去,后面factory通id就可以获得一个拥有全路径类名和成员变量的beanDefinition对象
…
自己实现一个解析xml,并注册的样例(待完成)
了解依赖注入的原理(待完成)