对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了一个对象)。例如:
程序定义了Student对象:

public class Student {
    private int id;
    private String name;
    private int age;
}

在其他模块使用的时候,要用new关键字实例化这个Student对象。

Student student = new Student();

使用这种方式会让其他模块对Student类这个模块产生了“依赖”,这种方式会造成代码维护的困难,例如,当Student的构造函数改变时,其他模块的代码也必须做相应改变。

工厂方法

如下图所示,工厂模式为了解决这个困难,设计了一种方式:用抽象方法(Factory.Manufacture())代替实例化过程(这个方法叫做工厂方法),真正实例化的过程要放到子类中。这样使得应用程序依赖的对象是一个抽象类(Product),而具体的实现(ProductA和ProductB)也依赖这个抽象类。这样就像形成了依赖倒置(以前应用程序依赖ProductA和ProductB,现在ProductA和ProductB依赖抽象类)。
工厂方法

Spring IoC

Spring则是将这个倒置的过程做到了极致,将应用程序依赖的所有实现过程全部扔出去,让这些实现通过Container以Bean的方式注入到应用程序中。

//1.加载 spring.xml 配置文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
//2.通过 id 值获取对象
Student stu = (Student) applicationContext.getBean("stu");
System.out.println(stu);

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

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值