Spring @Service生成bean名稱的規則 dubbo 找不到對應的bean
阿新 • • 發佈:2019-02-02
轉自:https://www.cnblogs.com/kevin-yuan/p/5437140.html
今天碰到一個問題,寫了一個@Service的bean,類名大致為:BKYInfoServcie.java
dubbo export服務的配置:
<dubbo:service interface="com.xxx.XxxService" ref="bKYInfoServcie" />
結果啟動報錯:找不到名為bKYInfoServcie的bean
bean的名字不是我預期的"bKYInfoServcie",臨時將bean的名字指定成了bKYInfoServcie來解決的,即:@Service("bKYInfoServcie")
但還是覺得比較奇怪,之前一直以為Spring對註解形式的bean的名字的預設處理就是將首字母小寫,再拼接後面的字元,但今天看來不是這樣的。
回來翻了一下原碼,原來還有另外的一個特殊處理:當類的名字是以兩個或以上的大寫字母開頭的話,bean的名字會與類名保持一致
/** * 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}) */ protected String buildDefaultBeanName(BeanDefinition definition) { String shortClassName = ClassUtils.getShortName(definition.getBeanClassName()); returnIntrospector.decapitalize(shortClassName); }
/** * 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. * <p> * Thus "FooBah" becomes "fooBah" and "X" becomes "x", but "URL" stays * as "URL". * * @param name The string to be decapitalized. * @return The decapitalized version of the string. */ public static String decapitalize(String name) { if (name == null || name.length() == 0) { return name; } // 如果發現類的前兩個字元都是大寫,則直接返回類名 if (name.length() > 1 && Character.isUpperCase(name.charAt(1)) && Character.isUpperCase(name.charAt(0))){ return name; } // 將類名的第一個字母轉成小寫,然後返回 char chars[] = name.toCharArray(); chars[0] = Character.toLowerCase(chars[0]); return new String(chars); }
@Service public class BJGLBaoJiaLogServiceImpl extends BaseServiceImpl<
比如這個類BJGLBaoJiaLogServiceImpl ,實際對應的是id='BJGLBaoJiaLogServiceImpl' 這個bean
spring通過型別注入所以沒這個問題