Spring IoC

Spring 是一个包含众多工具 IoC 容器

Spring 两大核心思想 : 1. IoC  2.AOP (重要面试题)

容器 : List/map 是装数据的容器

          Tomcat 是装web的容器

Spring 容器装的是对象

IoC 控制反转=>控制权反转=>创建对象的控制权交给了Spring

Spring 是 IoC 容器,也就是控制反转的容器,创建对象的控制权交给了 Spring ,由Spring 来帮我们创建管理这些对象

现在我们写一个案例,一辆车的生产,这是方法1,分成五个类

package com.example.ioc.ioc.v1;
public class Main {
    public static void main(String[] args) {
        Car car = new Car(17);
        car.run();
        Car car2 = new Car(19);
        car.run();
    }
}


package com.example.ioc.ioc.v1;
public class Car {
    private Framework framework;
    public Car(int size) {
        framework = new Framework(size);
        System.out.println("car init...");
    }
    public void run(){
        System.out.println("car run...");
    }
}


package com.example.ioc.ioc.v1;
public class Framework {
    private Bottom bottom;
    public Framework(int size) {
        bottom = new Bottom(size);
        System.out.println("framework init...");
    }
}


package com.example.ioc.ioc.v1;
public class Bottom {
    private Tire tire;
    public Bottom(int size){
        tire = new Tire(size);
        System.out.println("bottom init...");
    }
}


package com.example.ioc.ioc.v1;
public class Tire {
    private int size ;
    public Tire(int size){
        this.size = size;
        System.out.println("tire init...size:"+size);
    }
}

 下面是方法2:

package com.example.ioc.v2;
public class Main {
    public static void main(String[] args) {
        Tire tire = new Tire(17,"red");
        Bottom bottom = new Bottom(tire);
        Framework framework = new Framework(bottom);
        Car car = new Car(framework);
        car.run();
    }
}


package com.example.ioc.v2;
public class Car {
    private Framework framework;
    public Car(Framework framework) {
        this.framework = framework;
        System.out.println("car init...");
    }
    public void run(){
        System.out.println("car run...");
    }
}


package com.example.ioc.v2;
public class Framework {
    private Bottom bottom;
    public Framework(Bottom bottom) {
        this.bottom = bottom;
        System.out.println("framework init...");
    }
}


package com.example.ioc.v2;
public class Bottom {
    private Tire tire;
    public Bottom(Tire tire) {
        this.tire = tire;
        System.out.println("bottom init...");
    }
}


package com.example.ioc.v2;
public class Tire {
    private int size ;
    private String color;
    public Tire(int size,String color){
        this.size = size;
        this.color = color;
        System.out.println("tire init...size:"+size);
        System.out.println("tire init...color:"+color);
    }
}

方法二的耦合度更低,相互之间的影响更小

IoC 是一种思想,DI(依赖注入)是一种实现方式,比如我们对上一篇图书管理系统的代码进行修改Spring IoC_第1张图片

Spring IoC_第2张图片

你可能感兴趣的:(spring,java,面试)