戴着假发的程序员出品
@Bean的value和name属性
spring应用手册(第二部分)
@Bean源码
@org.springframework.core.annotation.AliasFor("name")
java.lang.String[] value() default {};
@org.springframework.core.annotation.AliasFor("value")
java.lang.String[] name() default {};
@Bean中的name和value属性 和 配置文件中的bean标签的name属性有同样的功能。
@Bean配置的类的默认id是方法的名称,但是我们可以通过value或者name给这个bean取别名。
注意:value和name属性不能并存。 而且如果配置了value或者name,那么我们将无法在通过方法名称获取这个bean了。
例如:
//配置ArticleService对象
@Bean(value="aservice")
//@Bean(name="aservice")
public ArticleService articleService(){
ArticleService articleService = new ArticleService();
//注入对应的属性
articleService.setArticleDAO(articleDAO());
articleService.setAutorDAO(authorDAO());
return articleService;
}
我们可以通过下面的方式获取service对象:
通过类型获取:
ArticleService bean = ac.getBean(ArticleService.class);
通过方法名称获取:
如果配置了value或者name,那么下面的操作会失效
ArticleService bean = (ArticleService) ac.getBean("articleService");
通过别名获取:
value和name配置别名,但是两个属性不能共存,也不能使用特殊符号,也不能同时配置多个别名
ArticleService bean = (ArticleService) ac.getBean("aservice");