Spring源码学习(三)默认标签的解析
默认标签的解析
分为四种:import,alias,bean,beans,在下面函数中进行
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); } }
parseDefaultElement
先看bean标签的解析与注册的大致过程
//BeanDefinitionParserDelegate:定义解析Element的各种方法 //BeanDefinitionHolder:Holder for a BeanDefinition with name and aliases.Can be registered as a placeholder for an inner bean. 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)); } }
processBeanDefinition
(1)先调用BeanDefinitionParserDelegate.parseBeanDefinitionElement(),对xml中的各种属性进行解析,方法返回BeanDefinitionHolder类型的实例bdHolder
(2)bdHolder下有自定义标签则对自定义标签进行解析
(3)对bdHolder进行注册
元素解析大致过程
@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) { checkNameUniqueness(beanName, aliases, ele); } //解析beanDefinition标签 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); return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray); } return null; }
parseBeanDefinitionElement
(1)获取标签中的id,name属性,当name不为空情况下获取其aliases
(2)解析其他的属性封装在AbstractBeanDefinition中并返回实例beanDefinition
(3)当bean无id属性则按照默认规则为其生成,并校验是否添加至aliases
(4)将beanDefinition,beanName,获取的aliases的aliasesArray封装至BeanDefinitionHolder中
具体解析了哪些其他标签
@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 { //创建GenericBeanDefinition类型的实例,用于承载属性的实例 AbstractBeanDefinition bd = createBeanDefinition(className, parent); //解析bean默认的各种属性 parseBeanDefinitionAttributes(ele, beanName, containingBean, bd); bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT)); //解析元数据 parseMetaElements(ele, bd); //解析lookup-method方法 parseLookupOverrideSubElements(ele, bd.getMethodOverrides()); //解析replaced-method方法 parseReplacedMethodSubElements(ele, bd.getMethodOverrides()); //解析构造函数 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; }
parseBeanDefinitionElement
bean的各种属性
/** * Apply the attributes of the given bean element to the given bean * definition. * @param ele bean declaration element * @param beanName bean name * @param containingBean containing bean definition * @return a bean definition initialized according to the bean element attributes */ 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. // 如果是内部bean定义,则从包含bean中获取默认值。 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 (isDefaultValue(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 (isDefaultValue(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; }
parseBeanDefinitionAttributes
具体看解析子元素meta标签
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); } } }
parseMetaElements
1 <bean id="tiger" class="com.vi.springbean.Tiger"> 2 <meta key="tigerKey" value="hello"/> 3 </bean>
eg:xml
具体看解析子元素lookup-method标签
public void parseLookupOverrideSubElements(Element beanEle, MethodOverrides overrides) { NodeList nl = beanEle.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); if (isCandidateElement(node) && nodeNameEquals(node, LOOKUP_METHOD_ELEMENT)) { Element ele = (Element) node; // <lookup-method name="" bean=""/> String methodName = ele.getAttribute(NAME_ATTRIBUTE); String beanRef = ele.getAttribute(BEAN_ELEMENT); LookupOverride override = new LookupOverride(methodName, beanRef); override.setSource(extractSource(ele)); overrides.addOverride(override); } } }
parseLookupOverrideSubElements
其实和meta标签解析大同小异
看一下lookup-method标签具体如何使用
public class Animal { public void sayHello(){ System.out.println("hello ··"); } }
父类
public class Tiger extends Animal { @Override public void sayHello() { System.out.println("hello 我是王者"); } }
子类
public class Mouse extends Animal{ @Override public void sayHello() { System.out.println("hello 我是生肖之首"); } }
子类
public abstract class LookUpTest { public abstract Animal getBean(); public void say(){ this.getBean().sayHello(); } }
调用方法
public class Test { @org.junit.Test public void test() { String path = "spring-config.xml"; ApplicationContext bf = new ClassPathXmlApplicationContext(path); LookUpTest bean = bf.getBean(LookUpTest.class); bean.say(); } }
测试方法
当xml配置如下:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="lookUpTest" class="com.vi.springbean.LookUpTest"> <lookup-method name="getBean" bean="tiger"></lookup-method> </bean> <bean id="mouse" class="com.vi.springbean.Mouse"></bean> <bean id="tiger" class="com.vi.springbean.Tiger"></bean> </beans>
xml配置0
运行结果:
hello 我是动物之王
当xml配置如下
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="lookUpTest" class="com.vi.springbean.LookUpTest"> <lookup-method name="getBean" bean="mouse"></lookup-method> </bean> <bean id="mouse" class="com.vi.springbean.Mouse"></bean> <bean id="tiger" class="com.vi.springbean.Tiger"></bean> </beans>
xml配置1
运行结果:
hello 我是生肖之首
这个配置完成的功能就是通过更改xml中lookup-method的配置,bean对应的对象作为getBean的返回
这是一种特殊的注入方式,被称为获取器注入,他是把一个方法声明为返回某种类型的bean,但实际要返回的bean是在xml文件中配置的。
好处是看解决程序依赖
具体看解析子元素replaced-method标签
/** * Parse replaced-method sub-elements of the given bean element. */ public void parseReplacedMethodSubElements(Element beanEle, MethodOverrides overrides) { NodeList nl = beanEle.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); if (isCandidateElement(node) && nodeNameEquals(node, REPLACED_METHOD_ELEMENT)) { Element replacedMethodEle = (Element) node; // <replace-method name="" replace=""/> String name = replacedMethodEle.getAttribute(NAME_ATTRIBUTE); String callback = replacedMethodEle.getAttribute(REPLACER_ATTRIBUTE); ReplaceOverride replaceOverride = new ReplaceOverride(name, callback); // Look for arg-type match elements. List<Element> argTypeEles = DomUtils.getChildElementsByTagName(replacedMethodEle, ARG_TYPE_ELEMENT); for (Element argTypeEle : argTypeEles) { String match = argTypeEle.getAttribute(ARG_TYPE_MATCH_ATTRIBUTE); match = (StringUtils.hasText(match) ? match : DomUtils.getTextValue(argTypeEle)); if (StringUtils.hasText(match)) { replaceOverride.addTypeIdentifier(match); } } replaceOverride.setSource(extractSource(replacedMethodEle)); overrides.addOverride(replaceOverride); } } }
parseReplacedMethodSubElements
看一下replaced-method标签具体如何使用
public class Replacer { public void changeMe(){ System.out.println("hello please change me"); } }
待替换方法
public class ReplaceTest implements MethodReplacer { @Override public Object reimplement(Object obj, Method method, Object[] args) throws Throwable { System.out.println("每个人都将成为王者"); return null; } }
替换的方法实现
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="replacer" class="com.vi.springbean.Replacer"> <replaced-method name="changeMe" replacer="replaceTest"></replaced-method> </bean> <bean id="replaceTest" class="com.vi.springbean.ReplaceTest"></bean> </beans>
xml配置
public class Test { @org.junit.Test public void test() { String path = "spring-config.xml"; ApplicationContext bf = new ClassPathXmlApplicationContext(path); Replacer bean = bf.getBean(Replacer.class); bean.changeMe(); } }
Test类
运行结果:
每个人都将成为王者
解析子元素constructor-arg
TODO
解析子元素property
TODO
注:GenericBeanDefinition,ChildBeanDefinition,RootBeanDefinition 都继承AbstractBeanDefinition
AbstractBeanDefinition 继承 BeanMetadataAttributeAccessor 实现 BeanDefinition
------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------
解析默认标签中的自定义标签元素
TODO
了解alias标签的解析
TODO
了解import标签的解析
TODO
了解beans标签的解析
递归调用beans标签的解析过程
已经是2020年的第二天了 时间过的很快 或许只有我一人觉得19年自己碌碌无为 20年加油吧