前言
本文主要讲述了Spring IoC和DI基础知识,并且通过实例解释了Spring IoC相较于传统开发模式更加解耦合
Spring
Spring是一个开源的框架,可以让开发进行的更加简单,是包含了众多工具方法的IoC容器
IoC容器
IoC容器就是控制权反转的意思,可以让我们在开发的过程中耦合更低
理解IoC 容器更加解耦合
题目:
客户需要定制一辆汽车,不同的客户对于车的要求有所不同,例如客户A要求车轮颜色为红色,客户B要求车轮大小为30,客户C要求车轮大小为20,颜色为红色
传统方式:
按照传统方式书写的代码每一次实例化对象都在各自的类中,若此时客户提出需求增加别的类型的要求,那么就需要对所有类的代码进行修改,满足每一位客户的需求就会比较麻烦,并且容易出错
public class NewCarExample {
public static void main(String[] args) {
Car car = new Car(20);
car.inti();
}
static class Car {
private int size;
public Car (int size){
this.size = size;
}
public void inti() {
Framework framework = new Framework(size);
framework.inti();
}
}
static class Framework {
private int size;
public Framework(int size){
this.size = size;
}
public void inti() {
Bottom bottom = new Bottom(size);
bottom.inti();
}
}
static class Bottom {
private int size;
public Bottom(int size){
this.size = size;
}
public void inti() {
Tire tire = new Tire(size);
tire.inti();
}
}
static class Tire {
private int size;
public Tire(int size){
this.size = size;
}
public void inti() {
System.out.println("轮胎尺寸:" + size);
}
}
}
IoC方式:
按照IoC方式进行开发就可以看到我们在代码实现中将所有的对象实例化都放在了main方法中进行,如果此时还需要对汽车有其他个性化要求时只需要对main方法和Tire类进行修改
public class Car {
public static void main(String[] args) {
Tire tire = new Tire(20,"黄色");
Bottom bottom = new Bottom(tire);
FrameWork frameWork = new FrameWork(bottom);
CarRun carRun = new CarRun(frameWork);
carRun.run();
}
public static class CarRun{
//车
private FrameWork frameWork;
public CarRun(FrameWork frameWork){
this.frameWork = frameWork;
}
public void run(){
frameWork.into();
}
}
public static class FrameWork{
//车身
private Bottom bottom;
public FrameWork(Bottom bottom){
this.bottom = bottom;
}
public void into(){
bottom.into();
}
}
public static class Bottom{
//底盘
private Tire tire;
public Bottom(Tire tire){
this.tire = tire;
}
public void into(){
tire.into();
}
}
public static class Tire{
//轮胎
private int size;
private String str;
public Tire(int size,String str){
this.size = size;
this.str = str;
}
public void into(){
System.out.println("轮胎尺寸:"+size);
System.out.println("轮胎颜色:"+str);
}
}
}
ID
DI是依赖注入(Dependency Injection)的缩写,就是IoC容器在运行期间,动态的将某种依赖关系注入到对象之中,就是在A类需要使用到B类时,主动的从Spring中获取对象