Bean的命名規(guī)則,定義在BeanNameGenerator接口的實(shí)現(xiàn)類
1.通過注解掃描Bean的命名規(guī)則
實(shí)現(xiàn)類:AnnotationBeanNameGenerator繼承了BeanNameGenerator
先看generateBeanName方法,這是入口
@Override
public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
if (definition instanceof AnnotatedBeanDefinition) {
String beanName = determineBeanNameFromAnnotation((AnnotatedBeanDefinition) definition);
if (StringUtils.hasText(beanName)) {
// Explicit bean name found.
return beanName;
}
}
// Fallback: generate a unique default bean name.
return buildDefaultBeanName(definition, registry);
}
這里判斷是否為注解類型的Bean,是的話通過注解內(nèi)容確定Bean名字;如果確認(rèn)不了,使用默認(rèn)方法生成Bean名字。
先看下怎么通過注解來判斷Bean名字,邏輯在determineBeanNameFromAnnotation方法里。
protected String determineBeanNameFromAnnotation(AnnotatedBeanDefinition annotatedDef) {
AnnotationMetadata amd = annotatedDef.getMetadata();
Set<String> types = amd.getAnnotationTypes();
String beanName = null;
for (String type : types) {
AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(amd, type);
if (isStereotypeWithNameValue(type, amd.getMetaAnnotationTypes(type), attributes)) {
Object value = attributes.get("value");
if (value instanceof String) {
String strVal = (String) value;
if (StringUtils.hasLength(strVal)) {
if (beanName != null && !strVal.equals(beanName)) {
throw new IllegalStateException("Stereotype annotations suggest inconsistent " +
"component names: '" + beanName + "' versus '" + strVal + "'");
}
beanName = strVal;
}
}
}
}
return beanName;
}
取到Bean的原信息里的注解信息,遍歷每個(gè)注解,確定注解是否符合條件的注解,取注解里的value值為Bean名字。
(符合條件:注解為@Component或者包含@Component或javax.annotation.ManagedBean或javax.inject.Named,且注解包含value屬性)
如果通過注解信息不能確認(rèn)Bean名字,那么就執(zhí)行默認(rèn)生成策略。
protected String buildDefaultBeanName(BeanDefinition definition) {
String shortClassName = ClassUtils.getShortName(definition.getBeanClassName());
return Introspector.decapitalize(shortClassName);
}
通過截取類的名字,變轉(zhuǎn)為符合Java變量名格式的字符串,作為Bean名字。下面是標(biāo)準(zhǔn)變量名的規(guī)則,變量名以小寫字母開頭,或者兩個(gè)大寫字母開頭。
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);
}

流程圖