1.内置BeanNameGenerator
BeanNameGenerator为BeanDefinition生成Bean名称
public interface BeanNameGenerator {
/**
* Generate a bean name for the given bean definition.
* @param definition the bean definition to generate a name for
* @param registry the bean definition registry that the given definition
* is supposed to be registered with
* @return the generated bean name
*/
String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry);
}
如下图
有2种策略,一种是是扫描xml(<context:component-scan />)时,一种是在注解扫描时(@ComponentScan)
测试代码:
public class AnnotationBeanNameGeneratorTests {
private BeanNameGenerator beanNameGenerator = new DefaultBeanNameGenerator();
//private BeanNameGenerator beanNameGenerator = new AnnotationBeanNameGenerator();
@Test
public void generateBeanNameWithNamedComponent() {
BeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry();
AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(ComponentWithName.class);
String beanName = this.beanNameGenerator.generateBeanName(bd, registry);
assertNotNull("The generated beanName must *never* be null.", beanName);
assertTrue("The generated beanName must *never* be blank.", StringUtils.hasText(beanName));
assertEquals("walden", beanName);
}
}
2.自定义BeanNameGenerator
可以指定nameGenerator属性来自定义bean的命名生成规则
public @interface ComponentScan {
Class<? extends BeanNameGenerator> nameGenerator() default BeanNameGenerator.class;
}
参考:
http://www.cnblogs.com/jason0529/p/5272265.html
http://www.cnblogs.com/jason0529/p/5274650.html
http://yunzhongxia.iteye.com/blog/898433