2.5@Bean的autowireCandidate属性

戴着假发的程序员出品  抖音ID:戴着假发的程序员 欢迎关注

[查看视频教程]

boolean autowireCandidate() default true;

autowireCandidate和配置文件bean标签的autowireCandidate属性一样,就是让其他的bean在按照类型注入时,忽略当前的bean。 默认值true。

我们可以在添加一个ArticleDAO的实现类:

 1 /**
 2  * @author 戴着假发的程序员
 3  *  
 4  * @description
 5  */
 6 public class ArticleDAO_other implements IArticleDAO {
 7     @Override
 8     public int save(String title) {
 9         System.out.println("ArticleDAO_other-save->保存文章:"+title);
10         return 1;
11     }
12 }

并且在AppConfig类中添加其注册信息:

1 @Bean
2 public static  IArticleDAO articleDAOOther(){
3     return new ArticleDAO_other();
4 }

注意:ArticleService的装配方式依然是byType

1 @Bean(name="aservice",autowire = Autowire.BY_TYPE)
2 public ArticleService articleService(){
3     ArticleService articleService = new ArticleService();
4     return articleService;
5 }

这时我们再测试:报错:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'aservice' defined in com. st.dk.demo3.AppConfig: Unsatisfied dependency expressed through bean property 'articleDAO'; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com. st.dk.demo3.dao.IArticleDAO' available: expected single matching bean but found 2: articleDAO,articleDAOOther

我们修改配置:

1 @Bean(autowireCandidate = false)
2 public static  IArticleDAO articleDAOOther(){
3     return new ArticleDAO_other();
4 }

测试会通过。

由于我们在articleDAOOther方法上方的@Bean中配置autowireCandidate为false,则spring在给ArticleService装配IArticleDAO时,就忽略了ArticleDAO_other,那么就只能找到一个ArticleDAO,那么自然就了。

注意:如果你是按照名称注入的,那么无论你是否配置autowireCandidate,都可以正常注入。

posted @ 2020-10-07 08:59  戴着假发的程序员0-1  阅读(1032)  评论(0编辑  收藏  举报