上一小节我们讲解了控制反转IOC的细节,接下来呢,我们学习依赖注解DI的细节。
依赖注入,是指IOC容器要为应用程序去提供运行时所依赖的资源,而资源指的就是对象。
在入门程序案例中,我们使用了@Autowired这个注解,完成了依赖注入的操作,而这个Autowired翻译过来叫:自动装配。
@Autowired注解,默认是按照类型进行自动装配的(去IOC容器中找某个类型的对象,然后完成注入操作)
入门程序举例:在EmpController运行的时候,就要到IOC容器当中去查找EmpService这个类型的对象,而我们的IOC容器中刚好有一个EmpService这个类型的对象,所以就找到了这个类型的对象完成注入操作。
那如果在IOC容器中,存在多个相同类型的bean对象,会出现什么情况呢?
程序运行会报错
如何解决上述问题呢?Spring提供了以下几种解决方案:
-
@Primary
-
@Qualifier
-
@Resource
使用@Primary注解:当存在多个相同类型的Bean注入时,加上@Primary注解,来确定默认的实现。
使用@Qualifier注解:指定当前要注入的bean对象。 在@Qualifier的value属性中,指定注入的bean的名称。
-
@Qualifier注解不能单独使用,必须配合@Autowired使用
使用@Resource注解:是按照bean的名称进行注入。通过name属性指定要注入的bean的名称。
面试题 : @Autowird 与 @Resource的区别
-
@Autowired 是spring框架提供的注解,而@Resource是JDK提供的注解
-
@Autowired 默认是按照类型注入,而@Resource是按照名称注入
自己的笔记
EmpServiceA和EmpServiceB都加了@Service 都交给spring管理
那
EmpService类型的Bean就有二个 一个EmpServiceA 一个 EmpServiceB
那现在地程序运行的时候,到底注入的是A还是B呢
启动报错
Description:
Field empService in com.itheima.controller.EmpController required a single bean, but 2 were found:
- empServiceA: defined in file [D:\front-end development\web_springboot\springboot-web-req-resp01\target\classes\com\itheima\service\impl\EmpServiceA.class]
- empServiceB: defined in file [D:\front-end development\web_springboot\springboot-web-req-resp01\target\classes\com\itheima\service\impl\EmpServiceB.class]
Action:
Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed
不能在进行自动装配 因为有超过二个EmpService的Bean
解决办法
第一种解决方案
@Primary
第二种解决方案
@Qualifier
第三种解决方案
@Resource
小结: