码迷,mamicode.com
首页 > 编程语言 > 详细

spring IOC控制反转和DI依赖注入

时间:2018-03-22 00:28:03      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:return   roc   occurs   nts   struct   rom   bean   als   however   

spring framework 的doc地址:https://docs.spring.io/spring/docs/current/spring-framework-reference/

spring framework 作为一个优秀的开源框架,其高扩展和高可用性毋庸置疑。这篇文章记录spring framework的控制反转。

  1.什么叫控制反转:在系统开发中我们要创建一个实例常见的做法就是new 一个对象(当然也还有其他创建实例的方法,eg 反射,工厂模式),这种通过程序员手动创建实例的行为称为正控制。spring的控制反转就是让程序员做的工作交给spring容器来处理。创建实例交给spring容器。这就叫控制反转。

  2.IOC (全程inversion  of Control)和 DI(Dependency injection ) :别看这是两个名称,一个控制反转,一个依赖注入。spring 的官网这样描述:

    This chapter covers the Spring Framework implementation of the Inversion of Control (IoC) [1] principle. IoC is also known as dependency injection (DI). It is a process whereby objects define their dependencies, that is, the other objects they work with, only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method. The container then injects those dependencies when it creates the bean. This process is fundamentally the inverse, hence the name Inversion of Control (IoC), of the bean itself controlling the instantiation or location of its dependencies by using direct construction of classes, or a mechanism such as the Service Locator pattern.

    IOC也被称为DI,他是一个对象定义其属性关系的过程。我们传入需要构造的实例的名称,属性 给spring的对象工厂,工厂方法将会去创建这个bean实例,创建的过程就是依赖传入的属性。程序员做的事情就是声明一些属性,创建实例就交给spring容器。spring 容器使用了工厂模式(建议看看设计模式之禅),程序员输入原料,spring生产出产品。

  3.spring的IOC容器做了什么?IOC容器对bean进行实例化,组装和管理。实例化自然不用说,组装是将bean和其他的bean建立依赖关系,比如一个Car 类 ,里面包含了Engin (发动机)类,Tyre(轮胎)类等,这是其他的类和这个类是有依赖关系的。管理:管理的是bean的作用范围和生命周期,默认的bean是无状态的bean,还有request、session、application、prototype等。

  4.配置bean被spring托管的形式有三种:一种是在xml配置,一种是注释,还有一种是properties文件(几乎没用过)。

  5.在应用中实例化bean容器的方式的方式:ClassPathXmlApplicationContext 和 FileSystemXmlApplicationContext ,这两个的构造函数只用传入xml配置路径(当然还有其他的构造函数)

  6.重点:bean的生命周期分为多种,这里讲一个场景:单例(bean-singleton)里面注入多例原型(bean-prototype):单例在容器初始化的时候就会被生成,仅仅只会生成一次,当将将多例原型注入单例的时候,多例也会在单例被实例化的时候实例化,当访问这个单例的时候,多例将不会成为有状态的bean,他跟随单例成为无状态的bean。这个很容易理解,不管是单例还是多例都只被实例化一次,表现出来的就是单例的行为。

    官网:However, suppose you want the singleton-scoped bean to acquire a new instance of the prototype-scoped bean repeatedly at runtime. You cannot dependency-inject a prototype-scoped bean into your singleton bean, because that injection occurs onlyonce, when the Spring container is instantiating the singleton bean and resolving and injecting its dependencies. If you need a new instance of a prototype bean at runtime more than once, see Method injection

  如果你是确实要这样做:spring 提供了如下实现

技术分享图片

本文讲了spring的ioc和di的概念,以及bean的定义,后面文章会具体讲bean怎么被实例化。

 

spring IOC控制反转和DI依赖注入

标签:return   roc   occurs   nts   struct   rom   bean   als   however   

原文地址:https://www.cnblogs.com/blogxiao/p/8617884.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!