Spring @Service生成bean名稱的規則


今天碰到一個問題,寫了一個@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());
        return Introspector.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); }
復制代碼

 

原文地址:https://www.cnblogs.com/kevin-yuan/p/5437140.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM