Spring(Spring Framework) 是一个开源的轻量级框架,是包含了众多工具方法的 IoC 容器。
什么是容器?
List、Map、Set是存储数据的容器
Tomcat 是Web容器
Spring 是IoC容器
IoC(Inversion of Control) ,译为控制反转。它不是什么技术,而是一种思想。在Java开发中,IoC意味着你将设计好的依赖对象B交给容器控制,而不是按照传统的方式,在你需要使用依赖对象 B 的对象 A 内部直接控制。
传统代码的开发:
/**
* 造一个车
*/
public class MakeCar {
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);
}
}
}
如果要修改车的尺寸:
/**
* 造一个车
*/
public class MakeCar {
public static void main(String[] args) {
Car car = new Car(20);
car.init();
}
/**
* 车类
*/
static class Car {
private Framework framework;
public Car(int size){
framework = new Framework(size);
}
public void init() {
framework.init();
}
}
/**
* 车身类
*/
static class Framework {
private Bottom bottom;
public Framework(int size){
bottom = new Bottom(size);
}
public void init() {
bottom.init();
}
}
/**
* 地盘类
*/
static class Bottom {
private Tire tire;
public Bottom(int size){
tire = new Tire(size);
}
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);
}
}
}
由以上代码可以看到,当底层的类被修改时,那么整个调用链上的所有的类都需要改变。代码的耦合性太高。
解决办法:
/**
* 造一辆车
*/
public class MakeNewCar {
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.init();
}
/**
* 车类
*/
static class Car{
private Framework framework;
public Car(Framework framework){
this.framework = framework;
}
public void init() {
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);
}
}
}
控制反转:改进之后的控制权发生反转,不再是上级对象创建并控制下级对象,而是把下级对象注入当前对象中,下级的控制权不再由上级所控制,即使下级类发生任何改变,当前类都是不受影响的。
DI(Dependency Injection),译为依赖注入。
依赖注入:就是IoC容器在运行时,动态的将某种依赖关系注入到对象中。
IoC是一种思想,DI就是IoC的具体实现
Spring的本质上是一个容器,容器才是Spring的核心,它具备容器的两个最基础的功能:
(1)将对象存入到容器
(2)从容器中取出对象
也就是说,Spring最核心的功能就是将对象存入到Spring中,再从Spring中获取到对象。
又因为Spring是一个IoC容器,那么它还具备管理对象的创建和销毁的权利。