面试Spring之IOC原理

你了解Spring IOC么

IOC:控制反转

->Spring Core最核心的部分

->需要先了解依赖注入

DI:设计行李箱

轮子<-------(依赖)底盘<-------(依赖)箱体<-------(依赖)行李箱

上层建筑依赖下层建筑

public class Luggage{

    private Framework framework ;
    Luggage(int size){
        this.framework = new framework (size);
    }
    public void move(){
        // ...相关逻辑
    }
}

public class Framework {

    private Bottom bottom;
    Framework (int size){
        this.bottom = new Bottom (size);
    }
}
public class Bottom{
    private Tire tire;
    Bottom(int size){
        this.tire = new Tire(size);
    }
}
public class Tire{
    private int size;
    Tire(int size){
        this.size = size;
    }
}
int size = 30;
Luggage luggage = new Luggage(size);
luggage.move();

依赖注入

含义:把底层类作为参数传递给上层类,实现上层对下层的“控制”

行李箱<-------(注入)箱体<-------(注入)底盘<-------(注入)轮子

public class Tire{
    private int size;
    Tire(){
        this.size = 20;
    }
}

public class Bottom{
    private Tire tire;
    Bottom(Tire tire){
        this.tire = tire;
    }
}
public class Framework{
    private Bottom bottom;
    Framework(Bottom bottom){
        this.bottom = bottom;
    }
}
public class Luggage{
    private Framework framework;
    Luggage(Framework framework){
        this.framework = framework;
    }
    public void move(){
        // ...相关逻辑
    }
}
int size = 30;
Tire tire = new Tire(size);
Bottom bottom = new Bottom(tire);
Framework framework = new Framework(bottom);
Luggage luggage = new Luggage(framework);
luggage.move();

依赖注入主要有以下的方式

->Setting

->Interface

->Constructor

->Annotation(注解)

依赖倒置原则,IOC,DI,IOC容器的关系

依赖倒置原则:高层模块不应该依赖于底层模块,两者都应该依赖其抽象------->(思路)IoC,离不开依赖注入的支撑,Spring框架基于IoC,提出容器的概念 ,对IoC最重要的就是容器了,容器管理者bean的生命周期,控制着bean的依赖注入 

IOC容器的优势

->避免在各处使用new来创建对象,并且可以做到统一维护

->创建实例的时候不需要了解其中的细节

 

IocC Container "工厂",我们就像是工厂的客户,查Config,Config,Config,Config。。。,到底了开始往上创建,注入,注入,住入,注入。。。

 

看视频《剑指Java面试》记录下的

你可能感兴趣的:(面试Spring之IOC原理)