戴着假發的程序員出品 抖音ID:戴着假發的程序員 歡迎關注
[查看視頻教程]
源碼:
1 @org.springframework.core.annotation.AliasFor("name") 2 java.lang.String[] value() default {}; 3 4 @org.springframework.core.annotation.AliasFor("value") 5 java.lang.String[] name() default {};
@Bean中的name和value屬性 和 配置文件中的bean標簽的name屬性有同樣的功能。
@Bean配置的類的默認id是方法的名稱,但是我們可以通過value或者name給這個bean取別名。
注意:value和name屬性不能並存。 而且如果配置了value或者name,那么我們將無法在通過方法名稱獲取這個bean了。
例如:
1 //配置ArticleService對象 2 @Bean(value="aservice") 3 //@Bean(name="aservice") 4 public ArticleService articleService(){ 5 ArticleService articleService = new ArticleService(); 6 //注入對應的屬性 7 articleService.setArticleDAO(articleDAO()); 8 articleService.setAutorDAO(authorDAO()); 9 return articleService; 10 }
我們可以通過下面的方式獲取service對象:
通過類型獲取:
1 ArticleService bean = ac.getBean(ArticleService.class);
通過方法名稱獲取:
如果配置了value或者name,那么下面的操作會失效
1 ArticleService bean = (ArticleService) ac.getBean("articleService");
通過別名獲取:
value和name配置別名,但是兩個屬性不能共存,也不能使用特殊符號,也不能同時配置多個別名
1 ArticleService bean = (ArticleService) ac.getBean("aservice");
