作者: 一字马胡
转载标志 【2017-12-28】
更新日志
日期 | 更新内容 | 备注 |
---|---|---|
2017-12-28 | 创建分析文档 | Spring源码分析系列文章(一) |
前言
Spring源码分析是一个系列,源码是Spring 4.X,本系列主要分析Spring的代码执行流程,过于细节的内容将不会涉及太多,主要是为了理清Spring的执行流程,比如Bean的解析是如何进行的,解析完成之后是如何进行加载的等等,对于在Bean的解析过程中涉及的一些细节很大可能不会在本系列的分析中找到,本系列的每一篇文章都是基于Spring源码的某条主要线索来进行,因为Spring的设计很复杂,并且它是一个工业级的优秀框架,所以未免会进行非常细节的考虑,如果想了解Spring源码中的某个细节,需要自行去研读源码来寻求答案,本系列的文章可以为那些希望对Spring的源码进行更为深度剖析的读者提供源码分析的思路,以至于不会在分析源码的时候迷失在复杂环绕的分支中找不到位置。
还需要说明的一点是,本系列文章都会包含大量的源码,有些源码将包含完整的方法内容,而有些会仅仅提供一条类似于:Class#method的索引,读者可以根据这些索引在源码中找到相应的位置,然后继续分析下去。对于一些方法,本系列的文章内容中出现的源码可能是经过处理的,比如会将异常处理的代码去掉,以及那些无关主要流程的代码去掉,留下那些和分析主线有关的代码,这样做的好处是可以避免贴出大量代码的困扰,并且可以使得每一个方法看起来都是清晰明了的,有助于理解正在分析的流程。
从例子出发
下面是一个使用Spring的简单例子,这个例子需要有一个model类,一个Spring xml配置文件,以及一个使用Spring的入口类:
public class ModelA {
private int value;
private String str;
@Override
public String toString() {
return "[" + value + ":" + str + "]";
}
public void setValue(int value) {
this.value = value;
}
public void setStr(String str) {
this.str = str;
}
}
public class BaseXmlDemo {
public static void main(String[] args) {
String file = "applicationContext.xml";
ApplicationContext context = new ClassPathXmlApplicationContext(file);
ModelA modelA = (ModelA) context.getBean("modelA");
System.out.println(modelA);
}
}
================Spring xml ============
<bean id="modelA" class="io.spring.ModelA">
<property name="value" value="1993"/>
<property name="str" value="hello"/>
</bean>
本文Spring源码分析的主题是Spring bean的解析,所谓bean的解析就是将我们的xml文件中的bean解析出来,上面的入口看到使用的是ClassPathXmlApplicationContext来获取ApplicationContext,所以,本次分析的入口也就从ClassPathXmlApplicationContext类中相应的构造函数开始。首先是调用了下面的构造函数:
public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
this(new String[] {configLocation}, true, null);
}
public ClassPathXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException {
super(parent);
setConfigLocations(configLocations);
if (refresh) {
refresh();
}
}
如果害怕迷失在源码中,可以选择一个我们关注的角色来跟踪代码,比如我们在bean解析分析的时候,首要关注的应该是我们传递进去的xml文件,所以可以在源码中跟踪我们传递的文件到底到了哪里,然后进行了什么操作。在上面的第二个构造函数中,首先一个比较关系的方法调用是setConfigLocations,这是将我们的xml文件保存起来了,bean的解析来源就是这个xml文件(所以可以看到底是哪个类在什么时候get了这个location)。当然,在这个构造函数中最为重要的一个方法调用是refresh方法,跟踪进去之后发现到达了AbstractApplicationContext#refresh(),下面是该方法的细节:
AbstractApplicationContext#refresh()
@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();
// 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();
}
}
}
这个方法中调用了大量的方法,但是现在我关系的只有一个:obtainFreshBeanFactory,下面是该方法的细节:
AbstractApplicationContext#obtainFreshBeanFactory
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (logger.isDebugEnabled()) {
logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
}
return beanFactory;
}
在这个方法里需要注意的方法调用是refreshBeanFactory,下面展示了某个refreshBeanFactory方法的实现细节:
AbstractRefreshableApplicationContext#refreshBeanFactory
protected final void refreshBeanFactory() throws BeansException {
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
try {
DefaultListableBeanFactory beanFactory = createBeanFactory();
beanFactory.setSerializationId(getId());
customizeBeanFactory(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);
}
}
在这个方法需要关系的是loadBeanDefinitions:
AbstractXmlApplicationContext#loadBeanDefinitions
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);
}
在这个方法内,首先new了一个XmlBeanDefinitionReader对象,根据名字可以猜测这个XmlBeanDefinitionReader对象的作用是实际进行xml文件读取并且进行解析的对象,后面再看具体是什么功能。还需要注意的是在new XmlBeanDefinitionReader对象的时候传递了当前的beanFactory,也就是说new出来的XmlBeanDefinitionReader其实是作为当前beanFactory的puppet而存在的,后续任何对该XmlBeanDefinitionReader的操作都会或多或少和我们设置的beanFactory有关。
然后,我们需要关系的一个方法调用是loadBeanDefinitions:
AbstractXmlApplicationContext#loadBeanDefinitions
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);
}
}
好吧,前面埋下的伏笔这里终于用上了,前面提到我们需要关系的是我们传递的xml文件到底是被谁以及到底是在什么时候进行get的,这里可以看到loadBeanDefinitions这个方法调用了getConfigResources来获取了我们传递的xml文件。为了降低分析源码的复杂度,我们假设第一个if是true,那么就会调用reader.loadBeanDefinitions进行解析操作。这个reader就是上面我们分析的那个new出来的XmlBeanDefinitionReader。按照猜测,下面应该开始进行xml的解析了吧?
AbstractBeanDefinitionReader#loadBeanDefinitions
public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException {
Assert.notNull(resources, "Resource array must not be null");
int counter = 0;
for (Resource resource : resources) {
counter += loadBeanDefinitions(resource);
}
return counter;
}
很遗憾的是开始没有开始进行xml解析,但是我们发现这个方法中调用了一个同名的方法loadBeanDefinitions,下面来看看这个方法的细节:
XmlBeanDefinitionReader#loadBeanDefinitions
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.isInfoEnabled()) {
logger.info("Loading XML bean definitions from " + encodedResource.getResource());
}
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();
}
}
}
就算走到这里,还是没有开始看到实际解析bean的细节,但是我们可以发现又一个关键的方法调用doLoadBeanDefinitions,下面是这个方法的实现细节:
XmlBeanDefinitionReader#doLoadBeanDefinitions
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
throws BeanDefinitionStoreException {
Document doc = doLoadDocument(inputSource, resource);
return registerBeanDefinitions(doc, resource);
}
走到这里,终于看到了我们想要看到的一点内容,那就是Document,这个Document对象是通过调用方法doLoadDocument来获取到的,大概的意思就是将xml加载到内容,并且解析成一个Document对象,后续的解析将基于该Document对象。前面那个doLoadDocument方法的细节就不分析了,直接看我们比较关心的registerBeanDefinitions方法:
XmlBeanDefinitionReader#registerBeanDefinitions
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;
}
这个方法中主要的流程代码是documentReader.registerBeanDefinitions,接着看这个方法的细节:
DefaultBeanDefinitionDocumentReader#registerBeanDefinitions
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
this.readerContext = readerContext;
logger.debug("Loading bean definitions");
Element root = doc.getDocumentElement();
doRegisterBeanDefinitions(root);
}
继续关注该方法中的关键方法调用:doRegisterBeanDefinitions
DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions
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);
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;
}
主要看最后的三个方法调用,分别代表在进行bean解析之前的以及之后的一些处理,主要看parseBeanDefinitions方法调用:
DefaultBeanDefinitionDocumentReader#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 ele = (Element) node;
if (delegate.isDefaultNamespace(ele)) {
parseDefaultElement(ele, delegate);
}
else {
delegate.parseCustomElement(ele);
}
}
}
}
else {
delegate.parseCustomElement(root);
}
}
从某种意义上来说,该方法是一个facade,从这个方法开始才是真正进行bean解析的内容,解析会分成默认标签的解析以及自定义标签的解析,关于Spring自定义标签的相关内容,可以参考文章浅析Spring自定义标签的使用,本文将主要关注默认标签的解析流程,涉及自定义标签的解析的内容可以自行研读相关代码,入口在上面的这个parseBeanDefinitions方法中的delegate.parseCustomElement(root)代码,默认标签的解析调用的方法是parseDefaultElement,下面来看这个方法的实现细节:
DefaultBeanDefinitionDocumentReader#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);
}
else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
processBeanDefinition(ele, delegate);
}
else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
// recurse
doRegisterBeanDefinitions(ele);
}
}
走到这里已经可以很清晰后续的流程了,默认标签这么几个:
- import
- alias
- bean
- beans
为了避免重复分析代码,挑选其中我们最常用的bean标签来进行后续流程的分析,如果是解析bean标签,会调用processBeanDefinition方法来进行,下面来看该方法的实现细节:
DefaultBeanDefinitionDocumentReader.processBeanDefinition
/**
* Process the given bean element, parsing the bean definition
* and registering it with the registry.
*/
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.
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));
}
}
该方法的第一个方法调用很值得关注,delegate.parseBeanDefinitionElement,下面来先看看该方法的实现细节:
BeanDefinitionParserDelegate#parseBeanDefinitionElement
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele) {
return parseBeanDefinitionElement(ele, null);
}
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, @Nullable BeanDefinition containingBean) {
String id = ele.getAttribute(ID_ATTRIBUTE);
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.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;
}
这个方法相对较长,看起来很复杂,来看看到底该方法干了什么:
- 获取bean的name和id以及aliases等属性
- 检测是否名字重复了,也就是说我们的bean的id是不能重复的。具体检测是否重复的方法是checkNameUniqueness,具体的细节可以看该方法的实现细节
- 调用parseBeanDefinitionElement获取该bean的AbstractBeanDefinition
- 根据上面这些信息来组装出一个BeanDefinitionHolder返回
下面来看一下parseBeanDefinitionElement这个方法的具体实现细节:
BeanDefinitionParserDelegate#parseBeanDefinitionElement
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 {
AbstractBeanDefinition bd = createBeanDefinition(className, parent);
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;
}
获取className以及parent信息,然后根据className和parent构造出一个AbstractBeanDefinition,调用的方法是createBeanDefinition,细节如下:
BeanDefinitionReaderUtils#createBeanDefinition
public static AbstractBeanDefinition createBeanDefinition(
@Nullable String parentName, @Nullable String className, @Nullable ClassLoader classLoader) throws ClassNotFoundException {
GenericBeanDefinition bd = new GenericBeanDefinition();
bd.setParentName(parentName);
if (className != null) {
if (classLoader != null) {
bd.setBeanClass(ClassUtils.forName(className, classLoader));
}
else {
bd.setBeanClassName(className);
}
}
return bd;
}
接着分别调用了一些关键方法来解析bean的相关内容,比如parseBeanDefinitionAttributes、parseMetaElements、parseConstructorArgElements,首先来看parseBeanDefinitionAttributes:
BeanDefinitionParserDelegate#parseBeanDefinitionAttributes
public AbstractBeanDefinition parseBeanDefinitionAttributes(Element ele, String beanName,
@Nullable BeanDefinition containingBean, AbstractBeanDefinition bd) {
if (ele.hasAttribute(SINGLETON_ATTRIBUTE)) {
error("Old 1.x 'singleton' attribute in use - upgrade to 'scope' declaration", ele);
}
else if (ele.hasAttribute(SCOPE_ATTRIBUTE)) {
bd.setScope(ele.getAttribute(SCOPE_ATTRIBUTE));
}
else if (containingBean != null) {
// Take default from containing bean in case of an inner bean definition.
bd.setScope(containingBean.getScope());
}
if (ele.hasAttribute(ABSTRACT_ATTRIBUTE)) {
bd.setAbstract(TRUE_VALUE.equals(ele.getAttribute(ABSTRACT_ATTRIBUTE)));
}
String lazyInit = ele.getAttribute(LAZY_INIT_ATTRIBUTE);
if (DEFAULT_VALUE.equals(lazyInit)) {
lazyInit = this.defaults.getLazyInit();
}
bd.setLazyInit(TRUE_VALUE.equals(lazyInit));
String autowire = ele.getAttribute(AUTOWIRE_ATTRIBUTE);
bd.setAutowireMode(getAutowireMode(autowire));
if (ele.hasAttribute(DEPENDS_ON_ATTRIBUTE)) {
String dependsOn = ele.getAttribute(DEPENDS_ON_ATTRIBUTE);
bd.setDependsOn(StringUtils.tokenizeToStringArray(dependsOn, MULTI_VALUE_ATTRIBUTE_DELIMITERS));
}
String autowireCandidate = ele.getAttribute(AUTOWIRE_CANDIDATE_ATTRIBUTE);
if ("".equals(autowireCandidate) || DEFAULT_VALUE.equals(autowireCandidate)) {
String candidatePattern = this.defaults.getAutowireCandidates();
if (candidatePattern != null) {
String[] patterns = StringUtils.commaDelimitedListToStringArray(candidatePattern);
bd.setAutowireCandidate(PatternMatchUtils.simpleMatch(patterns, beanName));
}
}
else {
bd.setAutowireCandidate(TRUE_VALUE.equals(autowireCandidate));
}
if (ele.hasAttribute(PRIMARY_ATTRIBUTE)) {
bd.setPrimary(TRUE_VALUE.equals(ele.getAttribute(PRIMARY_ATTRIBUTE)));
}
if (ele.hasAttribute(INIT_METHOD_ATTRIBUTE)) {
String initMethodName = ele.getAttribute(INIT_METHOD_ATTRIBUTE);
bd.setInitMethodName(initMethodName);
}
else if (this.defaults.getInitMethod() != null) {
bd.setInitMethodName(this.defaults.getInitMethod());
bd.setEnforceInitMethod(false);
}
if (ele.hasAttribute(DESTROY_METHOD_ATTRIBUTE)) {
String destroyMethodName = ele.getAttribute(DESTROY_METHOD_ATTRIBUTE);
bd.setDestroyMethodName(destroyMethodName);
}
else if (this.defaults.getDestroyMethod() != null) {
bd.setDestroyMethodName(this.defaults.getDestroyMethod());
bd.setEnforceDestroyMethod(false);
}
if (ele.hasAttribute(FACTORY_METHOD_ATTRIBUTE)) {
bd.setFactoryMethodName(ele.getAttribute(FACTORY_METHOD_ATTRIBUTE));
}
if (ele.hasAttribute(FACTORY_BEAN_ATTRIBUTE)) {
bd.setFactoryBeanName(ele.getAttribute(FACTORY_BEAN_ATTRIBUTE));
}
return bd;
}
可以很清楚的知道该方法到底在干什么,具体内容就不再赘述了,读一遍就知道具体的实现内容了,接着看parseMetaElements:
BeanDefinitionParserDelegate#parseMetaElements
public void parseMetaElements(Element ele, BeanMetadataAttributeAccessor attributeAccessor) {
NodeList nl = ele.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (isCandidateElement(node) && nodeNameEquals(node, META_ELEMENT)) {
Element metaElement = (Element) node;
String key = metaElement.getAttribute(KEY_ATTRIBUTE);
String value = metaElement.getAttribute(VALUE_ATTRIBUTE);
BeanMetadataAttribute attribute = new BeanMetadataAttribute(key, value);
attribute.setSource(extractSource(metaElement));
attributeAccessor.addMetadataAttribute(attribute);
}
}
}
最后是parseConstructorArgElements:
BeanDefinitionParserDelegate#parseConstructorArgElements
/**
* Parse constructor-arg sub-elements of the given bean element.
*/
public void parseConstructorArgElements(Element beanEle, BeanDefinition bd) {
NodeList nl = beanEle.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (isCandidateElement(node) && nodeNameEquals(node, CONSTRUCTOR_ARG_ELEMENT)) {
parseConstructorArgElement((Element) node, bd);
}
}
}
这里面又调用看了一个重要的方法parseConstructorArgElement,该方法很简单但是很长,所以在此不再贴出来了,可以跟踪进去看看到底该方法实现了些什么内容,以及到底是怎么实现的。其他的parseXXX方法就不再赘述了,点到为止。全部的parseXXX方法调用可以参考下面的代码:
现在回到processBeanDefinition方法,接着分析接下来的流程。执行完 delegate.parseBeanDefinitionElement(ele)之后获取到了一个BeanDefinitionHolder对象,接着来分析一个关键的方法BeanDefinitionReaderUtils.registerBeanDefinition,下面是它的实现细节:
BeanDefinitionReaderUtils#registerBeanDefinition
public static void registerBeanDefinition(
BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
throws BeanDefinitionStoreException {
// Register bean definition under primary name.
String beanName = definitionHolder.getBeanName();
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);
}
}
}
然后获取到了beanName,然后调用了BeanDefinitionRegistry对象的register方法进行bean注册,需要知道的一点是,走到这里,我们的bean已经解析完成了,也就是说,我们在xml里面配置的bean已经被解析好了,并且已经放到了内存中了,当然现在还需要将解析好的bean注册到Spring容器中去,下面来继续分析接下来的流程:
DefaultListableBeanFactory#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 {
if (hasBeanCreationStarted()) {
// Cannot modify startup-time collection elements anymore (for stable iteration)
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 {
// Still in startup registration phase
this.beanDefinitionMap.put(beanName, beanDefinition);
this.beanDefinitionNames.add(beanName);
this.manualSingletonNames.remove(beanName);
}
this.frozenBeanDefinitionNames = null;
}
if (oldBeanDefinition != null || containsSingleton(beanName)) {
resetBeanDefinition(beanName);
}
}
这个方法的意思大概是,检测是否已经有同名的bean被注册过了,如果被注册过了那么就要抛出异常,因为Spring不支持同名bean存在。中间通过了大量的判断,如果顺利的话,这个bean会被存储到一个map中去,这个map的定义如下:
/** Map of bean definition objects, keyed by bean name */
private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);
key是beanName,value就是解析好的BeanDefinition。到此,Spring源码解析中关于bean解析的内容就梳理完了,主要分析了bean标签的解析,自定义标签的解析并没有涉及,但是给出了参考链接可以参考,标签页给出了分析自定义标签解析的入口,可以根据入口继续进行自定义标签的解析流程分析。
本文粗线条的描述了Spring源码中关于bean解析的分析,没有涉及太多细节的内容,但是骨干清晰,可以清晰明了的理解Spring中bean的解析过程,包括如何将xml文件加载到内存中去,并且如何将xml文件内容进行解析,分成自定义标签和默认标签的解析,默认标签的解析比如bean、import等,通读全文,可以快速打通bean解析的全过程,中间虽然没有涉及太多细节的内容,并且都是挑选了全链路中的某条分支来进行分析,但是这样可以快速理清Spring的bean解析过程,后续会逐步完善该过程,逐步加入一些涉及细节的内容,来深度解析bean解析过程中的某些需要注意的点,以及bean解析过程和其他模块之间的交互关系等内容。
网友评论