Spring是什么?
抛开复杂的官方用语简单概述:
Spring是包含了众多工具方法的IOC容器
-----------------------------------------------------------------
什么是IoC?
IoC是Inversion of Control的缩写,意为控制反转
何为控制反转?
举个例子:
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);
}
}
}
我们会发现,整个代码是写死的,汽车依赖车身,车身依赖地盘,地盘依赖轮胎。如果你要改轮胎的大小,就需要找到轮胎类,将size修改。或者,你想指定一下轮胎的材料,就要再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);
}
}
}
对比一下:
改前
static class Car {
public void init() {
// 依赖⻋身
Framework framework = new Framework();
framework.init();
}
}
改后
static class Car {
private Framework framework;
public Car(Framework framework) {
this.framework = framework;
}
public void run() {
framework.init();
}
}
改前车身是在Car类里面自己生产好的,改后是直接将别人生产好的车身传给Car。
这样就做到了程序的解耦,不会像之前一样,动一发而牵全身。
DI(依赖注入)
IoC的一个重点是在系统运行中,动态的向某个对象提供它所需要的其他对象。这一点是通过DI(Dependency Injection,依赖注入)来实现的。就比如刚刚的汽车需要车身,我们就只需要告诉Spring我们需要一个车身,Spring就会制造一个车身,我们直接用就可以了,不需要直到车身是怎么制造的。
IoC与DI的区别就是:IoC是一种思想,DI是IoC具体的实现方式。