Spring IOC、DI的概念和@Autowired注入

本文详细探讨了Spring框架的IOC和DI概念,并解释了控制反转的实际含义。接着,深入分析了@Autowired注解的工作原理,指出其并不遵循byType和byName的自动装配模型,而是在源码层面有不同实现。同时,对比了@Autowired与@Resource的区别,强调了它们所使用的后置处理器差异。最后,简要介绍了XML配置中手动注入bean的四种方式。
摘要由CSDN通过智能技术生成

最近看到一位大神的视频讲解Spring的IOC、Bean的注入方式。打算整理一下,分享出来。

一、 Spring的IOC、DI概念

IOC 全称 Inversion of Control 控制反转,DI 全称 dependency injection 依赖注入。

很多博客文章都在表达一个意思

IOC:把创建实例的控制权交给框架,由框架创建实例(控制反转)并把实例分发给调用的程序(依赖注入)。

DI:把代码向对象属性或实例对象注入属性值或域属性的控制权限转给Spring容器进行控制。

从上面的文字描述结合实际的场景来说,好像就是这么一回事。因为我们在使用上的感觉来说,我们是没有使用new的关键字去实例化对象,也没有通set方法主动去设置属性,Spring都帮我们做了。

但是Spring官网的1.1. Introduction to the Spring IoC Container and Beans 章节有这么一段话:

This chapter covers the Spring Framework implementation of the Inversion of Control (IoC) principle. IoC is also known as dependency injection (DI).

谷歌翻译:本章介绍了控制反转(IoC)原理的Spring框架实现。 IoC也称为依赖注入(DI)。

下面是Introduction to the Spring IoC Container and Beans章节其中某一段的全文翻译。
在这里插入图片描述

至此,相信大家都会有各自的理解。具体章节地址:

https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#beans

二、Spring bean的@Autowired

有一些文章是这样写的,Autowired是先通过byType去查找bean,如果找不到就通过byName去查找。

其实byType、byName这两个概念是在Spring XML配置,才会有。具体可以看
在这里插入图片描述

Spring官网的1.4.5. Autowiring Collaborators 具体地址

https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#beans-factory-autowire

有这么一个表格关于 Autowiring modes(自动装配模型) 的描述

Mode Explanation
no (Default) No autowiring. Bean references must be defined by ref elements. Changing the default setting is not recommended for larger deployments, because specifying collaborators explicitly gives greater control and clarity. To some extent, it documents the structure of a system.
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值