文章目录:
1、spring 是什么
Spring 指的是
Spring Framework
(Spring 框架)它是⼀个开源框架
用一句话概括:Spring 是包含了众多工具方法的 IoC 容器
1.1、什么是容器
容器是容纳某种物品的基本装置:
List / Map ——> 数据存储容器
Tomcat ——> web 容器(运行 web 程序)
1.2、IoC 是什么
IoC,
Inversion of Control
,即 “控制反转”(原控制权在你,现在把控制权交出去)。控制的是一个一个类, 反转就是类的生命周期不由程序员来控制了, 而是交给这个 IoC 容器来控制.
1.2.1、传统程序开发
这个代码模拟造一个车:
public class NewCarExample {
public static void main(String[] args) {
Car car = new Car();
car.init();
}
/**
* 汽⻋对象
*/
static class Car {
public void init() {
// 依赖⻋身
Framework framework = new Framework();
framework.init();
}
}
/**
* ⻋身类
*/
static class Framework {
public void init() {
// 依赖底盘
Bottom bottom = new Bottom();
bottom.init();
}
}
/**
* 底盘类
*/
static class Bottom {
public void init() {
// 依赖轮胎
Tire tire = new Tire();
tire.init();
}
}
/**
* 轮胎类
*/
static class Tire {
// 尺⼨
private int size = 30;
public void init() {
System.out.println("轮胎尺⼨:" + size);
}
}
}
这样的代码中,车里有需要 new 框架,框架里 new 底盘,底盘里 new 轮胎,所以这个代码耦合性非常强
,如果后期需要改动需求(需要根据用户的需求来设计轮胎的大小),这时候 size 就不能是固定的 50 了,需要把 size 属性放置在 Tire 类的 init 方法中
static class Tire {
// 尺⼨
public void init(int size) {
System.out.println("轮胎尺⼨:" + size);
}
}
Tire 的控制权在 Bottom ,所以这里 init 方法的变化,会导致 Bottom 里面的 new Tire() 发生变化,会一直层层向上变化………………后期可能会有更多的需求变化,所以每次修改最底层的类会影响整个调用链变化,虽然可以实现但是成本比较大
static class Bottom {
public void init(int size) {
// 依赖轮胎
Tire tire = new Tire(size);
tire.init();
}
}
所以这里需要进行解耦合
,这里就是把控制权交出去了,当一个 bottom 类需要一个 Tire 类时,直接向去要即可,不需要关心其生命周期,这样底层的类再怎么变化都不会影响到整个调用链
public class IocCarExample {
public static void main(String[] args) {
Tire tire = new Tire(20);
Bottom bottom = new Bottom(tire);
Framework framework = new Framework(bottom);
Car car = new Car(framework);
car.run();
}
static class Car {
private Framework framework;
public Car(Framework framework) {
this.framework = framework;
}
public void run() {
framework.init();
}
}
static class Framework {
private Bottom bottom;
public Framework(Bottom bottom) {
this.bottom = bottom;
}
public void init() {
bottom.init();
}
}
static class Bottom {
private Tire tire;
public Bottom(Tire tire) {
this.tire = tire;
}
public void init() {
tire.init();
}
}
static class Tire {
private int size;
public Tire(int size) {
this.size = size;
}
public void init() {
System.out.println("轮胎:" + size);
}
}
}
两者对比:
IoC 的优点:
解耦合、对象(Bean)生命周期交给 IoC 来维护,作为程序员不需要再关注
1.3、Spring IoC
Spring IoC
最核心的功能:1、将 Bean 对象
存储到 Spring 中
2、将 Bean 对象从 Spring 中取出来
1.4、什么是 DI
DI :
Dependency Injection
译为:依赖注入依赖注入, 就是在 IoC容器 在运行的时候, 动态的将某种依赖关系注入到对象之中.
IoC 是“⽬标”也是⼀种思想,⽽⽬标和思想只是⼀种指导原则,最终还是要有可⾏的落地⽅案,⽽ DI 就属于具体的实现
2、总结:
2.1、Spring 是什么
Spring 是包含众多工具方法的 IoC 容器
——————————————————————
包含两个最为核心的功能:
1、将对象存储到 Spring 中
2、从 Spring 中取出对象
2.2、IoC 和 DI 的区别:
IoC :控制反转,是一种
思想
————————————————
DI :依赖注入,是一种实现
2.3、Spring 最为核心的功能:
1、将对象存储到 Spring 中
————————————————
2、从 Spring 中取出对象