Spring注解@Autowired、@Resource、@Qualifier使用及区别 解决:
- expected single matching bean but found 2
- No qualifying bean of type [java.lang.String] is defined: expected single matching bean but found 2:
这些错误都是由于Spring容器自动装配无法匹配合适的bean引起的,值得说明的是,在使用配置文件方式配置bean时,在配置文件中配置bean时,需要特别注意那个 name 属性,而不是 id 属性,文末举例。
在平时的spring项目中,经常看到@Autowired、@Resource、@Qualifier等注解,这篇文章就给大家分享一下我的使用经验。
1. @Autowired
使用@Autowired注解自动注入需要的引用,下面给出简单示例。
- 定义一个人类接口
package com.exc.demo.annotest;
public interface People {
String getSex();
}
- 分别创建“男人”和“女人”2个类来实现上边的人类接口
package com.exc.demo.annotest;
public class Man implements People {
@Override
public String getSex() {
return "男人";
}
}
package com.exc.demo.annotest;
public class Woman implements People {