Day05-13.分层解耦-IOC&DI-DI详情

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的名称”)

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值