1. 程式人生 > >spring註解@Component、@Service等自動生成bean的命名規則

spring註解@Component、@Service等自動生成bean的命名規則

參考連結:資訊來源

今天碰到一個問題,寫了一個@Service的bean,類名大致為:CUser

xml配置:

<context:component-scan base-package="com.xxx.xx.x"/>

結果啟動報錯:No bean named 'cUser' is defined,即找不到名為cUser的bean

bean的名字不是我預期的"cUser",臨時將bean的名字硬性指定成了cUser來解決的,即:@Service("cUser")

 在網上找了半天,看到有位兄弟說得很有道理,引用一下(以下內容引用自篇首連結):

    但還是覺得比較奇怪,之前一直以為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);
    }