spring源码系列一 IoC 和 DI

IoC 是什么

IoC:Inversion of Control 控制反转,也称依赖倒置(反转)
IoC 不是什么技术,而是一种设计思想。在 Java 开发中,IoC 意味着将你设计好的对象交给容器控制,而不是传统的在你的对象内部直接控制。

上例子:

public static void main(String[] args) {
    ServiceA serviceA = new ServiceA();
    serviceA.doService();
}

上面这种就是传统的方式,在用 ServiceA 的时候再去实例化 ServiceA。是程序主动去创建依赖对象。

IoC 是有专门一个容器来创建这些对象,即由 IoC 容器来控制对象的创建。

为何是反转:有反转就有正转,传统应用程序是由我们自己在对象中主动控制去直接获取依赖对象,也就是正转。

而反转则是由容器来帮忙创建及注入依赖对象;为何是反转?因为由容器帮我们查找及注入依赖对象,对象只是被动的接受依赖对象,所以是反转。

public class ServiceA {
    @Autowired
    ServiceB serviceB;

    public static void main(String[] args) {
        serviceB.doService();
    }
}

上面这个例子就是容器帮我们创建 ServiceB,我们直接使用就可以。

DI 是什么

DI—Dependency Injection,即“依赖注入”:组件之间依赖关系由容器在运行期决定,即由容器动态的将某个依赖关系注入到组件之中。就像上面的那个例子 @Autowired 一样。
依赖注入的目的是为了提升组件重用的频率,并为系统搭建一个灵活、可扩展的平台。通过依赖注入机制,我们只需要通过简单的配置,而无需任何代码就可指定目标需要的资源,完成自身的业务逻辑,而不需要关心具体的资源来自何处,由谁实现。

简单来说,IoC 是目的,DI 是手段。IoC 是指让生成类的方式由传统方式(new)反过来,既程序员不调用 new,需要类的时候由框架注入(DI),是同一件事不同层面的解读。

Spring 中 IoC 的设计

Beanfactory,IoC 容器 Bean 工厂

Spring 中用 Bean 创建、管理实例对象,用户需要实例对象时只需要向 IOC 容器获取就行了,不用自己去创建,从而达到与具体类解耦。

bean 是什么,bean 是组件,就是类对象!

Spring 通过 Bean 工厂去管理,创建所有的 Bean,即 Beanfactory。就是 spring 的 IoC 容器。
Bean 工厂对外提供获取 Bean 的接口。

Spring 源码:

//The root interface for accessing a Spring bean container.
public interface BeanFactory {
    ...
    //Return an instance, which may be shared or independent, of the specified bean.  
    Object getBean(String name) throws BeansException;
    ...
}

Spring 对该接口进行了扩展,比如 ListableBeanFactory 和 AutowireCapableBeanFactory 等,提供了一些其他功能。spring 工程的启动类中,ApplicationContext 也是继承了 ListableBeanFactory。可见 BeanFactory 是整个 spring 的核心。

BeanDefinitionRegistry, Bean 注册

说完 Bean 工厂,我们怎么能让 spring 容器知道我们需要哪些 Bean 呢? 这就需要 Bean 的注册定义接口,即 BeanDefinitionRegistry。

Spring 源码:

/*Interface for registries that hold bean definitions, for example RootBeanDefinition
 * and ChildBeanDefinition instances. Typically implemented by BeanFactories that
 * internally work with the AbstractBeanDefinition hierarchy.*/
public interface BeanDefinitionRegistry extends AliasRegistry {
    //Register a new bean definition with this registry.
    void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
            throws BeanDefinitionStoreException;
    //Remove the BeanDefinition for the given name.
    void removeBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;
    //Return the BeanDefinition for the given bean name.
    BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;
    //Check if this registry contains a bean definition with the given name.
    boolean containsBeanDefinition(String beanName);
    //Return the names of all beans defined in this registry.
    String[] getBeanDefinitionNames();
    //Return the number of beans defined in the registry.
    int getBeanDefinitionCount();   
    //Determine whether the given bean name is already in use within this registry, 
    //whether there is a local bean or alias registered under this name.
    boolean isBeanNameInUse(String beanName);
}

bean 定义 BeanDefinition 定义好了就需要告诉 IoC 容器(bean 工厂)
通过 bean 定义注册接口 BeanDefinitionRegistry 把 bean 定义 BeanDefinition 注册到 IoC 容器(bean 工厂) BeanFactory。
源码中的注释已经解释的很好了,我就不在这一一翻译了。

BeanDefinition, Bean 定义

Bean 的定义,告诉工厂该如何创建 Bean。

spring 源码:




/**
 * A BeanDefinition describes a bean instance, which has property values,
 * constructor argument values, and further information supplied by
 * concrete implementations.
 */
public interface BeanDefinition extends AttributeAccessor, BeanMetadataElement {

    /**
     * Scope identifier for the standard singleton scope: {@value}.
     */
    String SCOPE_SINGLETON = ConfigurableBeanFactory.SCOPE_SINGLETON;

    /**
     * Scope identifier for the standard prototype scope: {@value}.
     */
    String SCOPE_PROTOTYPE = ConfigurableBeanFactory.SCOPE_PROTOTYPE;


    ...

    /**
     * Set the name of the parent definition of this bean definition, if any.
     */
    void setParentName(@Nullable String parentName);

    /**
     * Return the name of the parent definition of this bean definition, if any.
     */
    @Nullable
    String getParentName();

    /**
     * Specify the bean class name of this bean definition.
     */
    void setBeanClassName(@Nullable String beanClassName);

    /**
     * Return the current bean class name of this bean definition.
     */
    @Nullable
    String getBeanClassName();

    /**
     * Override the target scope of this bean, specifying a new scope name.
     */
    void setScope(@Nullable String scope);

    /**
     * Return the name of the current target scope for this bean,
     * or {@code null} if not known yet.
     */
    @Nullable
    String getScope();

    /**
     * Set whether this bean should be lazily initialized.
     */
    void setLazyInit(boolean lazyInit);

    /**
     * Return whether this bean should be lazily initialized, i.e. not
     * eagerly instantiated on startup. Only applicable to a singleton bean.
     */
    boolean isLazyInit();

    /**
     * Specify the factory bean to use, if any.
     * This the name of the bean to call the specified factory method on.
     * @see #setFactoryMethodName
     */
    void setFactoryBeanName(@Nullable String factoryBeanName);

    /**
     * Return the factory bean name, if any.
     */
    @Nullable
    String getFactoryBeanName();

    /**
     * Specify a factory method, if any. This method will be invoked with
     * constructor arguments, or with no arguments if none are specified.
     * The method will be invoked on the specified factory bean, if any,
     * or otherwise as a static method on the local bean class.
     */
    void setFactoryMethodName(@Nullable String factoryMethodName);

    /**
     * Return a factory method, if any.
     */
    @Nullable
    String getFactoryMethodName();

    /**
     * Return the constructor argument values for this bean.
     */
    ConstructorArgumentValues getConstructorArgumentValues();

    /**
     * Return if there are constructor argument values defined for this bean.
     */
    default boolean hasConstructorArgumentValues() {
        return !getConstructorArgumentValues().isEmpty();
    }

    /**
     * Return the property values to be applied to a new instance of the bean.
     */
    MutablePropertyValues getPropertyValues();

    /**
     * Return if there are property values defined for this bean.
     */
    default boolean hasPropertyValues() {
        return !getPropertyValues().isEmpty();
    }

    /**
     * Set the name of the initializer method.
     */
    void setInitMethodName(@Nullable String initMethodName);

    /**
     * Return the name of the initializer method.
     */
    @Nullable
    String getInitMethodName();

    /**
     * Set the name of the destroy method.
     */
    void setDestroyMethodName(@Nullable String destroyMethodName);

    /**
     * Return the name of the destroy method.
     */
    @Nullable
    String getDestroyMethodName();

    /**
     * Set a human-readable description of this bean definition.
     * @since 5.1
     */
    void setDescription(@Nullable String description);

    /**
     * Return a human-readable description of this bean definition.
     */
    @Nullable
    String getDescription();

    /**
     * Return whether this a <b>Singleton</b>, with a single, shared instance
     */
    boolean isSingleton();

    /**
     * Return whether this a <b>Prototype</b>, with an independent instance
     */
    boolean isPrototype();
    ...

}

我并没有把全部代码都粘上来,具体的可以去看 spring 源码 只是把大体功能粘贴上来了。
主要就是一下功能:
-配置 Bean 的 Class 全路径;
-配置/获取 Bean 是否懒加载;
-配置/获取 FactoryBean 的名字;
-配置 Bean 的初始化方法、销毁方法;
-是否为单例或者原型;
-配置/获取 Bean 的依赖对象
-配置/获取 Bean 是否是自动装配。
等等。。

由 BeanDefinition 定义 Bean,然后 BeanDefinitionRegistry 来注册 Bean,最后 BeanFactory 来创建 Bean,这样 Spring 就完成了整个 Bean 的管理和创建,也实现了 IoC 的功能,在应用中用到 Bean 的时候,Spring 在通过依赖注入(DI)的方式给到程序使用。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335

推荐阅读更多精彩内容