对Spring的概念的一些理解:IoC和Bean

Spring Core Technologies 文档中对Spring的基本概念做了官方的定义,我在这些定义的基础上说一下自己个人的理解。

Inversion of Control (IoC)

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.

控制反转,也叫作依赖注入,是Spring的核心概念之一。
面对对象编程将各个功能模块拆成各个对象,应用程序在运行的时候需要使用其它功能模块,如果直接在程序中将其实例化(new了一个对象),就对这个模块产生了“依赖”,这种方式会造成代码维护的困难。
如下图所示,工厂模式为了解决这个困难,设计了一种方式:用抽象方法(Factory.Manufacture())代替实例化过程(这个方法叫做工厂方法),真正实例化的过程要放到子类中。这样使得应用程序依赖的对象是一个抽象类(Product),而具体的实现(ProductA和ProductB)也依赖这个抽象类。这样就像形成了依赖倒置(以前应用程序依赖ProductA和ProductB,现在ProductA和ProductB依赖抽象类)。
工厂方法
Spring则是将这个倒置的过程做到了极致,将应用程序依赖的所有实现全部扔出去,让这些实现通过Container以Bean的方式注入到应用程序中。依赖通过构造器声明、工厂方法声明、工厂方法实例化后的对象属性这3种方式被定义。
Spring依赖倒置

Bean

In Spring, the objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. Otherwise, a bean is simply one of many objects in your application. Beans, and the dependencies among them, are reflected in the configuration metadata used by a container.
Bean definitions correspond to the actual objects that make up your application. Typically you define service layer objects, data access objects (DAOs), presentation objects such as Struts Action instances, infrastructure objects such as Hibernate SessionFactories, JMS Queues, and so forth.

Beans就是通过IoC容器实例化、配置、组织到应用程序中的具体实现,是应用程序的骨架,下面列举几个具体的Bean实际对象:

  • service layer objects
  • data access objects (DAOs)
  • presentation objects such as Struts Action instances
  • infrastructure objects such as Hibernate SessionFactories, JMS Queues

猜你喜欢

转载自blog.csdn.net/sinat_34763749/article/details/80586218
今日推荐