攻城狮在路上(贰) Spring(二)--- Spring IoC概念介绍

一、IoC的概念
  IoC(控制反转)是Spring容器的核心。另一种解释是DI(依赖注入),即让调用类对某一个接口的依赖关系由第三方注入,以移除调用类对某一个接口实现类的一览。
  定义如此,由此可见,在面向接口编程的情况下,IoC可以很好的实现解耦,可以以配置的方式为程序提供所需要的接口实现类。
  在实际程序开发中,我们只需要提供对应的接口及实现类,然后通过Spring的配置文件或者注解完成对依赖类的装配。
二、IoC的类型
  1、通过构造函数
    此种方式的缺点是,在构造函数中注入之后一般会作为一个私有变量存储在调用类内,而调用类不见得每一个方法都需要该注入类。
  2、属性注入
    这是最为常见的方法,通过Setter方法实现。
  3、接口注入
    将调用类所有依赖注入的方法抽取到一个接口中,调用类通过实现该接口提供相应的注入方法。缺点是增加了一个接口。不提倡使用这种方式。
三、通过容器完成依赖关系注入
  Spring通过配置文件或注解描述类和类之间的依赖关系。下面是一个入门的Demo实例:

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xmlns:p="http://www.springframework.org/schema/p"
  xsi:schemaLocation="http://www.springframework.org/schema/beans 
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/context 
  http://www.springframework.org/schema/context/spring-context-3.0.xsd>
  <bean id="car" class="com.xxx.Car"/>
  <bean id="boss" class="com.xxx.Boss">
    <property name="car">
      <ref bean="car"></ref>
    </property>
  </bean>
</beans>

  然后通过new XmlBeanFactory("beans.xml");等方式即可启动容器,在启动容器时,Spring会根据配置文件的描述信息,自动实例化Bean并且完成依赖关系的装配。

原文地址:https://www.cnblogs.com/tq03/p/3791694.html