您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“如何實(shí)現(xiàn)Spring中生成Bean時(shí)默認(rèn)生成名稱”,感興趣的朋友不妨來(lái)看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來(lái)帶大家學(xué)習(xí)“如何實(shí)現(xiàn)Spring中生成Bean時(shí)默認(rèn)生成名稱”吧!
定義一個(gè)類如下:
@Componentpublic class MXTable{ ...... }復(fù)制代碼
通過(guò)ApplicationContext.getBean("mXTable")
獲取這個(gè)Bean對(duì)象,但是為NULL,導(dǎo)致調(diào)用的時(shí)候出現(xiàn)空指針異常。
在使用注解生成Bean的時(shí)候,如果沒(méi)有指定Bean的名稱,如@Componet("mytable")
,則Spring會(huì)使用默認(rèn)的名稱生成策略,具體源碼如下:
public class AnnotationBeanNameGenerator implements BeanNameGenerator { private static final String COMPONENT_ANNOTATION_CLASSNAME = "org.springframework.stereotype.Component"; public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) { if (definition instanceof AnnotatedBeanDefinition) { String beanName = determineBeanNameFromAnnotation((AnnotatedBeanDefinition) definition); if (StringUtils.hasText(beanName)) { // Explicit bean name found.return beanName; } } // Fallback: generate a unique default bean name.return buildDefaultBeanName(definition); } /** * Derive a bean name from one of the annotations on the class. * @param annotatedDef the annotation-aware bean definition * @return the bean name, or <code>null</code> if none is found */protected String determineBeanNameFromAnnotation(AnnotatedBeanDefinition annotatedDef) { AnnotationMetadata amd = annotatedDef.getMetadata(); Set<String> types = amd.getAnnotationTypes(); String beanName = null; for (String type : types) { Map<String, Object> attributes = amd.getAnnotationAttributes(type); if (isStereotypeWithNameValue(type, amd.getMetaAnnotationTypes(type), attributes)) { String value = (String) attributes.get("value"); if (StringUtils.hasLength(value)) { if (beanName != null && !value.equals(beanName)) { throw new IllegalStateException("Stereotype annotations suggest inconsistent " + "component names: '" + beanName + "' versus '" + value + "'"); } beanName = value; } } } return beanName; } /** * Check whether the given annotation is a stereotype that is allowed * to suggest a component name through its annotation <code>value()</code>. * @param annotationType the name of the annotation class to check * @param metaAnnotationTypes the names of meta-annotations on the given annotation * @param attributes the map of attributes for the given annotation * @return whether the annotation qualifies as a stereotype with component name */protected boolean isStereotypeWithNameValue(String annotationType, Set<String> metaAnnotationTypes, Map<String, Object> attributes) { boolean isStereotype = annotationType.equals(COMPONENT_ANNOTATION_CLASSNAME) || (metaAnnotationTypes != null && metaAnnotationTypes.contains(COMPONENT_ANNOTATION_CLASSNAME)) || annotationType.equals("javax.annotation.ManagedBean") || annotationType.equals("javax.inject.Named"); return (isStereotype && attributes != null && attributes.containsKey("value")); } /** * Derive a default bean name from the given bean definition. * <p>The default implementation simply builds a decapitalized version * of the short class name: e.g. "mypackage.MyJdbcDao" -> "myJdbcDao". * <p>Note that inner classes will thus have names of the form * "outerClassName.innerClassName", which because of the period in the * name may be an issue if you are autowiring by name. * @param definition the bean definition to build a bean name for * @return the default bean name (never <code>null</code>) */protected String buildDefaultBeanName(BeanDefinition definition) { String shortClassName = ClassUtils.getShortName(definition.getBeanClassName()); return Introspector.decapitalize(shortClassName); }復(fù)制代碼
Spring在給Bean生成名字的時(shí)候,會(huì)調(diào)用generateBeanName
方法,這個(gè)方法會(huì)先嘗試獲取注解括號(hào)中的名字,也就是用戶自定義的名稱,如果沒(méi)有獲取到,則調(diào)用buildDefaultBeanName
,用于生成默認(rèn)的名稱,這個(gè)方法會(huì)使用Introspector.decapitalize(shortClassName);
,問(wèn)題就在這個(gè)方法上,這個(gè)方法的API文檔如下:
public static String decapitalize(String name) Utility method to take a string and convert it to normal Java variable name capitalization. This normally means converting the first character from upper case to lower case, but in the (unusual) special case when there is more than one character and both the first and second characters are upper case, we leave it alone. Thus "FooBah" becomes "fooBah" and "X" becomes "x", but "URL" stays as "URL". Parameters: name - The string to be decapitalized. Returns: The decapitalized version of the string.
最重要的一句話翻譯過(guò)來(lái)是說(shuō):如果name的開(kāi)頭兩個(gè)及兩個(gè)以上字符為大寫,則不作處理并直接返回原來(lái)的名字,否則將名稱的首字母小寫后返回。
重命名類型名稱,如原來(lái)的MXTable,改成MxTable或者M(jìn)xtable等,反正避免開(kāi)頭兩個(gè)字母都是大寫;
getBean的參數(shù)使用MXTable;
在@Component中加上參數(shù),自定義Bean的名稱,如@Component("mxTable")
到此,相信大家對(duì)“如何實(shí)現(xiàn)Spring中生成Bean時(shí)默認(rèn)生成名稱”有了更深的了解,不妨來(lái)實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。