@Qualifier、@Primary

文章来自:https://felord.cn/spring-qualifier.html

以下是用于笔记记录。


使用@Autowired注解时可能会发生依赖注入冲突,比如当容器中有多个相同类型的Bean时,Spring不知道要注入哪个bean。
image


(1)@Autowired可以根据注入的变量名来寻找合适的Bean,如下面这种情况就不会发生冲突。
image


(2)使用 @Qulifier

// ①在注入时使用
@Autowired
@Qualifier("fooFormatter")
private Formatter formatter;

// ②在实现类使用
@Component
@Qualifier("fooFormatter")
public class FooFormatter implements Formatter {
	public String format() {
		return "foo";
	}
}

(3)使用 @Primary
当存在多个相同类型的 bean 时,使用该注解来定义首选项
image
此时如果发生冲突,则Spring默认注入的Bean是方法johnEmployee返回的Bean。
如果需要注入另外的Bean,使用@Qualifier可以实现。
当@Qualifier和@Primary同时存在时,@Qualifier具有优先权

posted @ 2025-06-22 23:24  巴啦啦飞上天  阅读(26)  评论(0)    收藏  举报