一、方法功能概述
// Tell the subclass to refresh the internal bean factory.
// 告诉子类刷新内部bean工厂
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
获得一个刷新后的bean工厂,返回一个ConfigurableListableBeanFactory对象,主要包含如下的操作:
-
如果bean工厂了,就销毁掉,关闭掉
-
创建一个新的bean工厂
-
设置序列化id和两个属性
-
加载BeanDefinition(解析xml中的bean,封装成BeanDefinition,放置到beanDefinition的map中)(重点!!!)
二、整体代码展示
//AbstractApplicationContext
/**
* Tell the subclass to refresh the internal bean factory.
* 告诉子类刷新内部bean工厂
* @return the fresh BeanFactory instance
* 返回刷新后的bean工厂实例
* @see #refreshBeanFactory()
* @see #getBeanFactory()
*/
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
//刷新bean工厂
refreshBeanFactory();
return getBeanFactory();
}
//refreshBeanFactory是一个抽象方法
//我们进入到其子类AbstractRefreshableApplicationContext中
//这边有个注意的点,如果是springmvc项目的话,会进到子类GenericApplicationContext中
@Override
protected final void refreshBeanFactory() throws BeansException {
//如果bean工厂了,就销毁掉,关闭掉
if (hasBeanFactory()) {
//其实就是调用一些集合的clear方法,解除对一些实例的引用
destroyBeans();
//关闭当前的beanFactory,其实就是将成员变量beanFactory设置为null
closeBeanFactory();
}
try {
//创建新的BeanFactory
DefaultListableBeanFactory beanFactory = createBeanFactory();
//为了序列话指定id,如果需要的话,让这个BeanFactory从id反序列化到BeanFactory对象
beanFactory.setSerializationId(getId());
/**
* 设置两个属性:
* 1. 是否允许覆盖同名称的不同定义的对象
* 2. 是否允许bean之间存在循环依赖
* 如果想改这两个属性值,在子类中重写该方法,设置属性
*/
customizeBeanFactory(beanFactory);
//根据配置,加载各个Bean,然后放到BeanFactory中
//注意,该方法的具体实现在子类中,所以xml和注解方式实现不同
loadBeanDefinitions(beanFactory);
synchronized (this.beanFactoryMonitor) {
this.beanFactory = beanFactory;
}
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}
三、详细代码解读、loadBeanDefinitions(重点!!!)
加载BeanDefinition
先看下调用流程图
这边loadBeanDefinitions有一堆重载方法,需要注意,容易乱
1、我们点击loadBeanDefinitions,进到子类AbstractXmlApplicationContext中
//AbstractXmlApplicationContext
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
beanDefinitionReader.setEnvironment(this.getEnvironment());
beanDefinitionReader.setResourceLoader(this);
/**
* 这个EntityResolver是jdk包里sax下的一个接口(SAX:Simple API for XML)
* 根据该类上的注解可知,这是一个解析实体的基础接口,实体其实代表的是xml中的标签对象
*
* 这个操作是:设置一个实现了EntityResolver的类,用来读取本地的xsd或者dtd文件,来完成相关的
* 解析工作
*/
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
//初始化beanDefinitionReader对象,此处设置配置文件是否需要验证
initBeanDefinitionReader(beanDefinitionReader);
//点这里
loadBeanDefinitions(beanDefinitionReader);
}
2、继续点loadBeanDefinitions(这是方法的重载!)
//AbstractXmlApplicationContext
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
Resource[] configResources = getConfigResources();
//这里一般是进不来了,取决于构造函数是否调用了设置configResources的那个
if (configResources != null) {
reader.loadBeanDefinitions(configResources);
}
String[] configLocations = getConfigLocations();
if (configLocations != null) {
//点这里
reader.loadBeanDefinitions(configLocations);
}
}
3、这里分Resource和String,点String进到AbstractBeanDefinitionReader类中
//AbstractBeanDefinitionReader
@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;
}
4、继续点loadBeanDefinitions
//AbstractBeanDefinitionReader
@Override
public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {
//第二个参数叫实际资源
return loadBeanDefinitions(location, null);
}
5、继续点loadBeanDefinitions
//AbstractBeanDefinitionReader
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) {
try {
//获取资源,这里要注意,AbstractApplicationContext实例化的时候会设置resourcePatternResolver为PathMatchingResourcePatternResolver这个类,所以这里往里点的时候,最终会到这个类中的getResources,具体作用就是匹配文件,整理成Resource对象
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 {
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;
}
}
6、继续点loadBeanDefinitions,进到类BeanDefinitionReader的子类XmlBeanDefinitionReader中
//XmlBeanDefinitionReader
@Override
public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
return loadBeanDefinitions(new EncodedResource(resource));
}
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 {
//开始从Resource中获取inputStream
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();
}
}
}
7、这里的doLoadBeanDefinitions才算进入到核心方法,之前的都是方法的重载,熟悉设计模式的同学还能发现其中运用了一些适配器的设计思想
//XmlBeanDefinitionReader
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
throws BeanDefinitionStoreException {
try {
//将流读取成一个文档对象
//内部有个getValidationModeForResource方法会分辨文件是dtd还是xsd
//内部其实就是解析xml文件返回文档对象,不必深究,有兴趣的可以看看
Document doc = doLoadDocument(inputSource, resource);
//把文档中各种节点读取出来解析成beanDefinition对象
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);
}
}
8、点击registerBeanDefinitions进去看
//XmlBeanDefinitionReader
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;
}
9、点击registerBeanDefinitions进入子类DefaultBeanDefinitionDocumentReader中看
//DefaultBeanDefinitionDocumentReader
@Override
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
this.readerContext = readerContext;
//真正做解析的方法
doRegisterBeanDefinitions(doc.getDocumentElement());
}
10、继续点击doRegisterBeanDefinitions进去
//DefaultBeanDefinitionDocumentReader
protected void doRegisterBeanDefinitions(Element root) {
BeanDefinitionParserDelegate parent = this.delegate;
this.delegate = createDelegate(getReaderContext(), root, parent);
//是否默认命名空间
if (this.delegate.isDefaultNamespace(root)) {
//是否包含profile属性
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.isDebugEnabled()) {
logger.debug("Skipped XML bean definition file due to specified profiles [" + profileSpec +
"] not matching: " + getReaderContext().getResource());
}
return;
}
}
}
//空方法,给子类扩展实现
preProcessXml(root);
//解析BeanDefinition,传入根节点
parseBeanDefinitions(root, this.delegate);
//空方法,给子类扩展实现
postProcessXml(root);
this.delegate = parent;
}
11、点击parseBeanDefinitions进去
//DefaultBeanDefinitionDocumentReader
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
if (delegate.isDefaultNamespace(root)) {
//获取子节点
NodeList nl = root.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element ele = (Element) node;
if (delegate.isDefaultNamespace(ele)) {
//有些是spring默认带的,<import />、<alias />、<bean />、<beans />这些
parseDefaultElement(ele, delegate);
}
else {
//其他标签,比如<mvc />、<task />、<context />、<aop />这些
delegate.parseCustomElement(ele);
}
}
}
}
else {
delegate.parseCustomElement(root);
}
}
12、点击parseDefaultElement进去可以看到默认命名空间
//DefaultBeanDefinitionDocumentReader
private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
//处理<import />标签
importBeanDefinitionResource(ele);
}
else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
//处理<alias />标签
processAliasRegistration(ele);
}
else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
//处理<bean />标签
processBeanDefinition(ele, delegate);
}
else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
//处理<beans />标签
doRegisterBeanDefinitions(ele);
}
}
public static final String ALIAS_ATTRIBUTE = "alias";
public static final String IMPORT_ELEMENT = "import";
public static final String BEAN_ELEMENT = "bean";
public static final String NESTED_BEANS_ELEMENT = "beans";
13、我们重点关注标签,所以点击processBeanDefinition进去
//DefaultBeanDefinitionDocumentReader
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
//BeanDefinitionHolder里包含了BeanDefinition、bean的名字和别名,用于向容器注册
//此处是通过BeanDefinitionParserDelegate对xml中元素解析得到BeanDefinitionHolder
BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
if (bdHolder != null) {
bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
try {
// 注册
BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
}
catch (BeanDefinitionStoreException ex) {
getReaderContext().error("Failed to register bean definition with name '" +
bdHolder.getBeanName() + "'", ele, ex);
}
getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
}
}
14、点击parseBeanDefinitionElement进去,到类BeanDefinitionParserDelegate中
//BeanDefinitionParserDelegate
@Nullable
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele) {
return parseBeanDefinitionElement(ele, null);
}
@Nullable
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, @Nullable BeanDefinition containingBean) {
//解析id
String id = ele.getAttribute(ID_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));
}
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) {
//判断名字是否唯一,在同一个xml中不能出现重复的bean名称
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);
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);
return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
}
return null;
}
15、继续点击parseBeanDefinitionElement进去
//BeanDefinitionParserDelegate
@Nullable
public AbstractBeanDefinition parseBeanDefinitionElement(
Element ele, String beanName, @Nullable BeanDefinition containingBean) {
this.parseState.push(new BeanEntry(beanName));
String className = null;
if (ele.hasAttribute(CLASS_ATTRIBUTE)) {
className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
}
String parent = null;
if (ele.hasAttribute(PARENT_ATTRIBUTE)) {
parent = ele.getAttribute(PARENT_ATTRIBUTE);
}
try {
//创建BeanDefinition,实际创建的是AbstractBeanDefinition的子类对象GenericBeanDefinition
AbstractBeanDefinition bd = createBeanDefinition(className, parent);
//解析bean标签的其他属性
parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
//设置description属性,description标签
bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));
//解析<meta />标签
parseMetaElements(ele, bd);
//解析<lookup-method />标签
parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
//解析<replaced-method />标签
parseReplacedMethodSubElements(ele, bd.getMethodOverrides());
//解析<constructor-arg />标签
parseConstructorArgElements(ele, bd);
//解析<property />标签
parsePropertyElements(ele, bd);
//解析<qualifier />标签
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;
}
16、至此BeanDefinitionHolder创建完成,下面回到第13步,点击registerBeanDefinition看下,到类BeanDefinitionReaderUtils中
//BeanDefinitionReaderUtils
public static void registerBeanDefinition(BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry) throws BeanDefinitionStoreException {
String beanName = definitionHolder.getBeanName();
//注册BeanDefinition
registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());
//注册别名,不然根据别名找不到bean
String[] aliases = definitionHolder.getAliases();
if (aliases != null) {
for (String alias : aliases) {
registry.registerAlias(beanName, alias);
}
}
}
17、再点击registerBeanDefinition,进到DefaultListableBeanFactory类的registerBeanDefinition方法
//DefaultListableBeanFactory
@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);
//处理已经注册的bean的情况,如果包含了相同名称的bean
if (existingDefinition != null) {
//如果不允许覆盖,就抛异常
if (!isAllowBeanDefinitionOverriding()) {
throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
}
else if (existingDefinition.getRole() < beanDefinition.getRole()) {
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 + "]");
}
}
//放到map里去
this.beanDefinitionMap.put(beanName, beanDefinition);
}
else {
//如果map里没有
if (hasBeanCreationStarted()) {
synchronized (this.beanDefinitionMap) {
this.beanDefinitionMap.put(beanName, beanDefinition);
List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
updatedDefinitions.addAll(this.beanDefinitionNames);
updatedDefinitions.add(beanName);
this.beanDefinitionNames = updatedDefinitions;
if (this.manualSingletonNames.contains(beanName)) {
Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames);
updatedSingletons.remove(beanName);
this.manualSingletonNames = updatedSingletons;
}
}
}
else {
this.beanDefinitionMap.put(beanName, beanDefinition);
this.beanDefinitionNames.add(beanName);
this.manualSingletonNames.remove(beanName);
}
this.frozenBeanDefinitionNames = null;
}
if (existingDefinition != null || containsSingleton(beanName)) {
resetBeanDefinition(beanName);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/154519.html