您好,登錄后才能下訂單哦!
這篇文章主要講解了“Spring實現解析默認標簽的方法”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“Spring實現解析默認標簽的方法”吧!
parseDefaultElement(ele, delegate); 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); } //解析beans標簽,遞歸處理 else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) { doRegisterBeanDefinitions(ele); } } protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) { //1.委托BeanDefinitionPaserDelegate類進行元素解析,將BeanDefinition封裝進BeanDefinitionHolder里面 //包含class、name、id屬性 BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele); if (bdHolder != null) { //2.若默認標簽的子節點下有自定義屬性,還需要再對自定義標簽解析 bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder); try { //3.委托BeanDefinitionReaderUtils注冊 BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry()); } //4.發出響應事件,通知想關心的監聽事件 getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder)); } }
BeanDefinition是一個接口,其抽象實現類為AbstractBeanDefinition,有三個子類,分別為RootBeanDefinition、ChildBeanDefinition 和GenericBeanDefinition. BeanDefinition是配置文件bean元素在容器中的內部表現形式,和bean中屬性一一對應.Spring通過 BeanDefinition將配置文件中的bean配置信息轉換為容器的內部表示,并將這些信息注冊到BeanDefinitionRegistry中,它就是Spring 配置信息的內存數據庫,是一個Map,后續操作直接從該BeanDefinitionRegistry中讀取配置信息.
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele) { return parseBeanDefinitionElement(ele, null); }
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, BeanDefinition containingBean) { //解析id屬性 String id = ele.getAttribute(ID_ATTRIBUTE); //解析name屬性 String nameAttr = ele.getAttribute(NAME_ATTRIBUTE); //若nameAttr不為空,解析別名屬性 List<String> aliases = new ArrayList<String>(); if (StringUtils.hasLength(nameAttr)) { String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS); aliases.addAll(Arrays.asList(nameArr)); } String beanName = id; //若沒有指定id屬性,使用別名的第一個代替 if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) { beanName = aliases.remove(0); } 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); String beanClassName = beanDefinition.getBeanClassName(); if (beanClassName != null && beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() && !this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) { aliases.add(beanClassName); } } } } String[] aliasesArray = StringUtils.toStringArray(aliases); return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray); } return null; }
public AbstractBeanDefinition parseBeanDefinitionElement(Element ele, String beanName, BeanDefinition containingBean) { String className = null; //解析className屬性 if (ele.hasAttribute(CLASS_ATTRIBUTE)) { className = ele.getAttribute(CLASS_ATTRIBUTE).trim(); } try { String parent = null; //解析parent屬性 if (ele.hasAttribute(PARENT_ATTRIBUTE)) { parent = ele.getAttribute(PARENT_ATTRIBUTE); } //創建用于承載屬性的GenericBeanDefinition,直接new的,并set傳進去的參數 AbstractBeanDefinition bd = createBeanDefinition(className, parent); //1.硬編碼解析bean的各種屬性 parseBeanDefinitionAttributes(ele, beanName, containingBean, bd); //2.解析description bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT)); //3.解析元數據 parseMetaElements(ele, bd); //4.解析lookup-method屬性,見附錄1,實際要返回的bean是在配置文件里面配置的 parseLookupOverrideSubElements(ele, bd.getMethodOverrides()); //5.解析replace-method屬性,不但可以動態地替換返回實體的bean,而且還能動態地更改原有方法的邏輯 parseReplacedMethodSubElements(ele, bd.getMethodOverrides()); //6.解析構造函數參數,property元素和qualifier元素 parseConstructorArgElements(ele, bd); parsePropertyElements(ele, bd); parseQualifierElements(ele, bd); bd.setResource(this.readerContext.getResource()); bd.setSource(extractSource(ele)); return bd; } }
步驟1:硬編碼解析bean的各種屬性
public AbstractBeanDefinition parseBeanDefinitionAttributes(Element ele, String beanName,BeanDefinition containingBean, AbstractBeanDefinition bd) { //解析scope屬性 if (ele.hasAttribute(SCOPE_ATTRIBUTE)) { bd.setScope(ele.getAttribute(SCOPE_ATTRIBUTE)); if (ele.hasAttribute(SINGLETON_ATTRIBUTE)) { error("Specify either 'scope' or 'singleton', not both", ele); } } //解析singleton屬性 else if (ele.hasAttribute(SINGLETON_ATTRIBUTE)) { bd.setScope(TRUE_VALUE.equals(ele.getAttribute(SINGLETON_ATTRIBUTE)) ? BeanDefinition.SCOPE_SINGLETON : BeanDefinition.SCOPE_PROTOTYPE); } else if (containingBean != null) { bd.setScope(containingBean.getScope()); } if (ele.hasAttribute(ABSTRACT_ATTRIBUTE)) { bd.setAbstract(TRUE_VALUE.equals(ele.getAttribute(ABSTRACT_ATTRIBUTE))); } //解析lazy-init屬性,若不設置或者設置成其他字符都會設置為false String lazyInit = ele.getAttribute(LAZY_INIT_ATTRIBUTE); if (DEFAULT_VALUE.equals(lazyInit)) { lazyInit = this.defaults.getLazyInit(); } bd.setLazyInit(TRUE_VALUE.equals(lazyInit)); //解析autowire屬性 String autowire = ele.getAttribute(AUTOWIRE_ATTRIBUTE); bd.setAutowireMode(getAutowireMode(autowire)); String dependencyCheck = ele.getAttribute(DEPENDENCY_CHECK_ATTRIBUTE); bd.setDependencyCheck(getDependencyCheck(dependencyCheck)); 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))); } //解析init-method屬性 if (ele.hasAttribute(INIT_METHOD_ATTRIBUTE)) { String initMethodName = ele.getAttribute(INIT_METHOD_ATTRIBUTE); if (!"".equals(initMethodName)) { bd.setInitMethodName(initMethodName); } } else { if (this.defaults.getInitMethod() != null) { bd.setInitMethodName(this.defaults.getInitMethod()); bd.setEnforceInitMethod(false); } } //解析destroy-method屬性 if (ele.hasAttribute(DESTROY_METHOD_ATTRIBUTE)) { String destroyMethodName = ele.getAttribute(DESTROY_METHOD_ATTRIBUTE); if (!"".equals(destroyMethodName)) { bd.setDestroyMethodName(destroyMethodName); } } else { if (this.defaults.getDestroyMethod() != null) { bd.setDestroyMethodName(this.defaults.getDestroyMethod()); bd.setEnforceDestroyMethod(false); } } //解析factory-method屬性 if (ele.hasAttribute(FACTORY_METHOD_ATTRIBUTE)) { bd.setFactoryMethodName(ele.getAttribute(FACTORY_METHOD_ATTRIBUTE)); } //解析factory-bean屬性 if (ele.hasAttribute(FACTORY_BEAN_ATTRIBUTE)) { bd.setFactoryBeanName(ele.getAttribute(FACTORY_BEAN_ATTRIBUTE)); } return bd; }
步驟4、5:見附錄1、2 步驟6:解析構造函數參數
上述解析后的數據都放在AbstractBeanDefinition中.
AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);
public abstract class AbstractBeanDefinition extends BeanMetadataAttributeAccessor implements BeanDefinition, Cloneable { private volatile Object beanClass; private String scope = SCOPE_DEFAULT; private boolean singleton = true; private boolean prototype = false; private boolean abstractFlag = false; private boolean lazyInit = false; private int autowireMode = AUTOWIRE_NO; private int dependencyCheck = DEPENDENCY_CHECK_NONE; private String[] dependsOn; //構造函數屬性 private ConstructorArgumentValues constructorArgumentValues; //普通屬性集合 private MutablePropertyValues propertyValues; //方法重寫的持有者,記錄lookup-method、replace-method元素 private MethodOverrides methodOverrides = new MethodOverrides(); private String factoryBeanName; private String factoryMethodName; private String initMethodName; private String destroyMethodName; //是否執行init-method和destroy-method private boolean enforceInitMethod = true; private boolean enforceDestroyMethod = true; }
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) { //解析BeanDefinition BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele); if (bdHolder != null) { bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder); try { //注冊BeanDefinition到registry BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry()); } //通知監聽器解析及完成注冊,當程序開發人員需要對注冊BeanDefinition事件進行監聽時可以通過注冊監聽器的方 //式并將處理邏輯寫入監聽器中,目前Spring中沒有對此事件做任何邏輯處理 getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder)); } }
public static void registerBeanDefinition(BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry){ String beanName = definitionHolder.getBeanName(); //使用beanName做唯一標識注冊 registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition()); String[] aliases = definitionHolder.getAliases(); if (aliases != null) { for (String aliase : aliases) { //使用別名做注冊 registry.registerAlias(beanName, aliase); } } }
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws BeanDefinitionStoreException { if (beanDefinition instanceof AbstractBeanDefinition) { try { //做校驗,拋異常部分已刪除 ((AbstractBeanDefinition) beanDefinition).validate(); } } //beanDefinitionMap就是存放注冊信息的全局變量,會存在并發訪問的情況,加鎖,它是ConcurrentHashMap //Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(64); synchronized (this.beanDefinitionMap) { Object oldBeanDefinition = this.beanDefinitionMap.get(beanName); //處理已經注冊beanName的情況 if (oldBeanDefinition != null) { if (!this.allowBeanDefinitionOverriding) { //此處代碼簡略了,不允許覆蓋則拋異常,允許覆蓋則記錄下日志 } } else { this.beanDefinitionNames.add(beanName); this.frozenBeanDefinitionNames = null; } //真正進行注冊 this.beanDefinitionMap.put(beanName, beanDefinition); } //清除緩存 resetBeanDefinition(beanName); }
protected void processAliasRegistration(Element ele) { //獲取beanName String name = ele.getAttribute(NAME_ATTRIBUTE); //獲取別名alias String alias = ele.getAttribute(ALIAS_ATTRIBUTE); boolean valid = true; //之前有一些校驗,刪掉了 if (valid) { try { //注冊 getReaderContext().getRegistry().registerAlias(name, alias); } getReaderContext().fireAliasRegistered(name, alias, extractSource(ele)); } }
protected void importBeanDefinitionResource(Element ele) { //解析resource屬性,形如<import resource=”***.xml”/> String location = ele.getAttribute(RESOURCE_ATTRIBUTE); //不存在直接返回 if (!StringUtils.hasText(location)) { getReaderContext().error("Resource location must not be empty", ele); return; } location = environment.resolveRequiredPlaceholders(location); Set<Resource> actualResources = new LinkedHashSet<Resource>(4); //判斷是相對路徑還是絕對路徑 boolean absoluteLocation = false; try { absoluteLocation = ResourcePatternUtils.isUrl(location) || ResourceUtils.toURI(location).isAbsolute(); } if (absoluteLocation) { try { //是絕對路徑,直接調用loadBeanDefinitions加載BeanDefinition,遞歸操作 int importCount = getReaderContext().getReader().loadBeanDefinitions(location, actualResources); } }else { try { int importCount; //計算出絕對路徑,進行loadBeanDefinitons Resource relativeResource = getReaderContext().getResource().createRelative(location); if (relativeResource.exists()) { importCount = getReaderContext().getReader().loadBeanDefinitions(relativeResource); actualResources.add(relativeResource); } else { String baseLocation = getReaderContext().getResource().getURL().toString(); importCount = getReaderContext().getReader().loadBeanDefinitions( StringUtils.applyRelativePath(baseLocation, location), actualResources); } } } Resource[] actResArray = actualResources.toArray(new Resource[actualResources.size()]); getReaderContext().fireImportProcessed(location, actResArray, extractSource(ele)); }
附錄1:解析lookup-method
public class User { public void showMe(){ System.out.println("I am a User"); } } public class Teacher extends User{ @Override public void showMe() { System.out.println("I am a teacher"); } } public abstract class GetBeanTest { public void showMe(){ this.getBean().showMe(); } public abstract User getBean(); }
<bean id="getBeanTest" class="com.lwh.spring.look.GetBeanTest"> <lookup-method name="getBean" bean="teacher"/> </bean> <bean id="teacher" class="com.lwh.spring.look.Teacher"/>
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; //獲取要修飾的方法 String methodName = ele.getAttribute(NAME_ATTRIBUTE); //獲取配置返回的bean String beanRef = ele.getAttribute(BEAN_ELEMENT); LookupOverride override = new LookupOverride(methodName, beanRef); override.setSource(extractSource(ele)); overrides.addOverride(override); } } }
附錄2:解析replace-method
public class TestChangeMethod { public void changeMe(){ System.out.println("changeMe"); } } public class TestMethodReplacer implements MethodReplacer{ public Object reimplement(Object obj, Method method, Object[] args) throws Throwable { System.out.println("我替換了原有的方法"); return null; } }
<bean id="testChangeMethod" class="com.lwh.spring.replace.TestChangeMethod"> <replaced-method name="changeMe" replacer="replacer"/> </bean> <bean id="replacer" class="com.lwh.spring.replace.TestMethodReplacer"/>
public void parseReplacedMethodSubElements(Element beanEle, MethodOverrides overrides) { NodeList nl = beanEle.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); //僅當在Spring默認bean的子元素下且為replace-method時才有效 if (isCandidateElement(node) && nodeNameEquals(node, REPLACED_METHOD_ELEMENT)) { Element replacedMethodEle = (Element) node; //提取要替換的舊的方法,changeMe String name = replacedMethodEle.getAttribute(NAME_ATTRIBUTE); //提取對應的新的替換方法,replacer 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); } } }
感謝各位的閱讀,以上就是“Spring實現解析默認標簽的方法”的內容了,經過本文的學習后,相信大家對Spring實現解析默認標簽的方法這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。