spring注解@Component、@Service等自动生成bean的命名规则

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

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);
}。

相关文档
最新文档