对spring DI(依赖注入)的理解

来源:互联网 发布:淘宝长安cs95中网改装 编辑:程序博客网 时间:2024/06/05 18:25

学习spring是在一年前了,现在把自己对spring中DI的理解写下来!

DI,Dependency Injection,许多人又把它叫做IOC,inversion of control,其实个人感觉意思差不太多,只是说法上有些不同罢了。

 DI是spring的核心功能之一,实现该功能主要有以下几个步骤:


     (1)spring读取配置文件(spring.xml)并将读取结果经过一系列的转换(xml->stream->encodeResource->document....具体看源码)最后在spring的核心类org.springframework.factory.beanfactory里注册写入内存,这里我们主要写入三部分,一是对象元,二是依赖原,三是配置信息


     (2)spring调用abstractbeanfactory的docreatebean方法后又调用乐儿一些其他的方法如createbeaninstance等 最终返回了一个对象的实例

     (3)spring建立缓存,并将上边创建的实例放入缓存

      (4)需要时拿出传给对象


spring的DI机制使得程序之间的耦合性大大降低,程序得而可配置性增强,通过配置文件就能对程序内部的类进行随意装配,提高了程序的灵活性和代码的复用率。


既然DI用起来这么舒服是不是任何对象都需要spring注入呢?

    官方是这么说的:

     Typically you will have bean definitions for your service layer(层) objects, your data access objects (DAOs), presentation objects such as Struts Action instances, infrastructure(基础设施) objects such as HibernateSessionFactories, JMS Queues, and so forth. Typically one does not configure fine-grained domain objects in the container, because it is usually the responsibility of DAOs and business logic to create/load domain objects.

   有道给翻译下:通常你会为你的服务层bean定义对象,你的数据访问对象(dao)、表示对象(如Struts Action实例、基础设施对象(如Hibernate SessionFactories,JMS队列等等,通常不配置细粒度的域对象的容器,因为它通常是dao的责任和业务逻辑创建/负载域对象。