使用spring注解形式注入bean,通过@Component、@Repository、 @Service和@Controller注解类,文档中说“注解如果没有指定bean的名字,默认为小写开头的类名”。例如类名是MyClass,则spring返回myClass的bean名。
但是如果类名前两个字母都是大写,则返回的bean名也是大写,即类名是MYClass,bean名也是MYClass。
举例:
@Component
public class MYClass{
}
获取MYClass spring bean:
ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
MYClass object = (MYClass)ctx.getBean("MYClass");
附Spring源码:
/**
* 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) {
//如果@Service定义了名字,直接返回定义的名字; e.g. @service("abc"),直接返回abc
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);
}