问题如下:今天工作中有一个类的命名为XPersonService,我获取bean的时候代码如下
AnnotationConfigApplicationContext config = new AnnotationConfigApplicationContext(AppConfig.class);
XpersonService xPersonService = (XpersonService) config.getBean("xPersonService");
但是报错了:
Exception in thread “main” org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named ‘xPersonService’ available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:681)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1218)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1109)
at Main.main(Main.java:10)
所以这样是获取不到的,我就追踪到源码里面看了一下,发现了点东西
/**
* 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);
}
所以总结beanName的生成规则如下:
1.当类的首字母和第二个字母都是大写时,返回类的原值,及我这里应该写成config.getBean(“XPersonService”)。
2.默认的情况下是将类的首字母小写,其余的字母不变。