最近看到一位大神的视频讲解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 def |