Day05-13.分层解耦-IOC&DI-DI详情
1.DI依赖注入详解:
依赖注入指的是IOC容器要为应用程序提供运行时所依赖的资源,资源指的就是对象。入门程序中,我们通过注解@Autowired就完成了依赖注入的操作,Autowired翻译过来叫自动装配,默认是安总类型装配的,也就是说要去IOC容器中去找这个类型的bean对象,然后完成注入。如果一个类型的bean对象有两个,就会报错。
2.bean注入:
1.@Autowired注解,默认是按照类型进行,如果存在多个相同类型的bean,将会报出如下错误:
Field empService in com.itheima.springbootwebreqresp.controller.EmpController required a single bean, but 2 were found:
- empServiceA: defined in file [C:\Users\IDEA\IdeaProjects\itheima_web_project\springboot-web-req-resp\target\classes\com\itheima\springbootwebreqresp\Service\Impl\EmpServiceA.class]
- empServiceB: defined in file [C:\Users\IDEA\IdeaProjects\itheima_web_project\springboot-web-req-resp\target\classes\com\itheima\springbootwebreqresp\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
2.通过以下几种方案来解决:
1.@Primary:用来设置bean的优先级,要想让哪个bean生效,可以在这个类上再加一个注解@Primary
@Primary
@Service
public class EmpServiceA implements EmpService{
}
2.Qualifier:在@Qualifier注解里面指定bean的名字(默认名字是类名首字母小写)
@RestController
public class EmpController{
@Qualifier("emoServiceA")
@Autowired
private EmpService empService;
}
3.Resource:这个注解是按照名称注入的,而@Autowired是按照类型进行注入的。
@RestController
public class EmpController{
@Resource(name = "empServiceB")
private EmpService empService;
}
Autowired、Qualifier等这些注解是Spring框架提供的,但是Resource这个注解是JDK提供的。
3.小结:
1.依赖注入的注解:
1.@Autowired:默认按照类型自动装配
2.如果同类型的bean存在多个:
1.@Primary
2.@Autowired + @Qualifier(“bean的名称”)
3.@Resource(name = “bean的名称”)