Spring IoC

IoC(Inversion of Control),控制反转,就是由容器控制程序之间的关系,而非传统实现中,由程序代码直接控制。这也就是所谓“控制反转”的概念所在:控制权由应用代码中转到了外部容器,控制权的转移,就是所谓反转。
 
关于控制反转和依赖注入,知乎作者Sevenvidia讲的非常生动形象

要了解控制反转( Inversion of Control ), 我觉得有必要先了解软件设计的一个重要思想:依赖倒置原则(Dependency Inversion Principle )


什么是依赖倒置原则?假设我们设计一辆汽车:先设计轮子,然后根据轮子大小设计底盘,接着根据底盘设计车身,最后根据车身设计好整个汽车。这里就出现了一个“依赖”关系:汽车依赖车身,车身依赖底盘,底盘依赖轮子。


这样的设计看起来没问题,但是可维护性却很低。假设设计完工之后,上司却突然说根据市场需求的变动,要我们把车子的轮子设计都改大一码。这下我们就蛋疼了:因为我们是根据轮子的尺寸设计的底盘,轮子的尺寸一改,底盘的设计就得修改;同样因为我们是根据底盘设计的车身,那么车身也得改,同理汽车设计也得改——整个设计几乎都得改!

我们现在换一种思路。我们先设计汽车的大概样子,然后根据汽车的样子来设计车身,根据车身来设计底盘,最后根据底盘来设计轮子。这时候,依赖关系就倒置过来了:轮子依赖底盘, 底盘依赖车身, 车身依赖汽车。

这时候,上司再说要改动轮子的设计,我们就只需要改动轮子的设计,而不需要动底盘,车身,汽车的设计了。

这就是依赖倒置原则——把原本的高层建筑依赖底层建筑“倒置”过来,变成底层建筑依赖高层建筑。高层建筑决定需要什么,底层去实现这样的需求,但是高层并不用管底层是怎么实现的。这样就不会出现前面的“牵一发动全身”的情况。

控制反转(Inversion of Control) 就是依赖倒置原则的一种代码设计的思路。具体采用的方法就是所谓的依赖注入(Dependency Injection)。其实这些概念初次接触都会感到云里雾里的。

这里我们是采用的构造函数传入的方式进行的依赖注入。其实还有另外两种方法:Setter传递接口传递。这里就不多讲了,核心思路都是一样的,都是为了实现控制反转

看到这里你应该能理解什么控制反转和依赖注入了。那什么是控制反转容器(IoC Container)呢?其实上面的例子中,对车类进行初始化的那段代码发生的地方,就是控制反转容器。

显然你也应该观察到了,因为采用了依赖注入,在初始化的过程中就不可避免的会写大量的new。这里IoC容器就解决了这个问题。这个容器可以自动对你的代码进行初始化,你只需要维护一个Configuration(可以是xml可以是一段代码),而不用每次初始化一辆车都要亲手去写那一大段初始化的代码。这是引入IoC Container的第一个好处。

IoC Container的第二个好处是:我们在创建实例的时候不需要了解其中的细节。在上面的例子中,我们自己手动创建一个车instance时候,是从底层往上层new的:

这个过程中,我们需要了解整个Car/Framework/Bottom/Tire类构造函数是怎么定义的,才能一步一步new/注入。

而IoC Container在进行这个工作的时候是反过来的,它先从最上层开始往下找依赖关系,到达最底层之后再往上一步一步new(有点像深度优先遍历):

这里IoC Container可以直接隐藏具体的创建实例的细节,在我们来看它就像一个工厂:

我们就像是工厂的客户。我们只需要向工厂请求一个Car实例,然后它就给我们按照Config创建了一个Car实例。我们完全不用管这个Car实例是怎么一步一步被创建出来。

实际项目中,有的Service Class可能是十年前写的,有几百个类作为它的底层。假设我们新写的一个API需要实例化这个Service,我们总不可能回头去搞清楚这几百个类的构造函数吧?IoC Container的这个特性就很完美的解决了这类问题,大大增加了项目的可维护性且降低了开发难度。

这里只是很粗略的讲了一下我自己对IoC和DI的理解。主要的目的是在于最大限度避免晦涩难懂的专业词汇,用尽量简洁,通俗,直观的例子来解释这些概念。如果让大家能有一个类似“哦!原来就是这么个玩意嘛!”的印象,我觉得就OK了。想要深入了解的话,可以上网查阅一些更权威的资料。这里推荐一下 Dependency injection Inversion of Control Containers and the Dependency Injection pattern 这两篇文章,讲的很好很详细。


  • 传统编程和IoC的对比

传统编程:决定使用哪个具体的实现类的控制权在调用类本身,在编译阶段就确定了。
IoC模式:调用类只依赖接口,而不依赖具体的实现类,减少了耦合。控制权交给了容器,在运行的时候才由容器决定将具体的实现动态的“注入”到调用类的对象中。

  • 用途

对于Spring的用途很多,但是Spring的核心和经典我们可以简化为三部分:
1、IoC容器可以将对象之间的依赖关系交由Spring管理,进行控制。
2、AOP方便进行面向切面编程,是oop的扩展,想加什么功能直接加。
3、能够集成各种优秀的框架,struts、Hibernate等等。

  • IoC的优缺点

优点:

1、把对象的创建和依赖关系定义在了XML文件中,我们改变子类的实现变得异常简单。
2、控制反转减轻了对象之间的耦合度,减轻了对象之间的依赖关系,增加了系统的灵活性,可维护性,以及可移植性等等。

缺点:

1、生成对象的方式变复杂了(事实上操作还是挺简单的),对于不习惯这种方式的人,会觉得有些别扭和不直观。
2、创建对象因为使用了反射技术,在效率上有些损耗。但相对于IoC提高的维护性和灵活性来说,这点损耗是微不足道的,除非某对象的生成对效率要求特别高。

Spring的核心就是依赖注入。Spring支持的注入方式主要有两种:setter注入(setter injection)和构造器注入(constructor injection)。

Setter注入

通过Spring的XML配置文件初始化UserBean。

1)首先创建UserBean

 1 public class UserBean {
 2     private String name;
 3     private Integer age;
 4     public String getName() {
 5         return name;
 6     }
 7     public void setName(String name) {
 8         this.name = name;
 9     }
10     public Integer getAge() {
11         return age;
12     }
13     public void setAge(Integer age) {
14         this.age = age;
15     }
16 }

2)在Spring的配置文件test.xml中配置UserBean

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"  
 3     xmlns:mvc="http://www.springframework.org/schema/mvc"  
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 5     xmlns:p="http://www.springframework.org/schema/p"  
 6     xmlns:context="http://www.springframework.org/schema/context"  
 7     xmlns:aop="http://www.springframework.org/schema/aop" 
 8     xmlns:tx="http://www.springframework.org/schema/tx" 
 9     xsi:schemaLocation="   
10            http://www.springframework.org/schema/beans   
11            http://www.springframework.org/schema/beans/spring-beans.xsd   
12            http://www.springframework.org/schema/context   
13            http://www.springframework.org/schema/context/spring-context.xsd  
14            http://www.springframework.org/schema/mvc   
15            http://www.springframework.org/schema/mvc/spring-mvc.xsd
16            http://www.springframework.org/schema/aop 
17            http://www.springframework.org/schema/aop/spring-aop.xsd
18            http://www.springframework.org/schema/tx 
19            http://www.springframework.org/schema/tx/spring-tx.xsd
20            ">                 
21      <bean id="user" class="com.zhwy.misp.bean.UserBean">
22          <property name="name" value="tomcat"></property>
23          <property name="age" value="18"></property>
24      </bean>
25  </beans>

3)测试类Test

 1 import org.springframework.context.ApplicationContext;
 2 import org.springframework.context.support.FileSystemXmlApplicationContext;
 3 import com.zhwy.misp.bean.UserBean;
 4 
 5 public class Test {
 6     public static void main(String[] agrs) {
 7         String name = "test.xml";
 8         String configLocation = ClassLoader.getSystemResource(name).getPath();
 9         ApplicationContext context = new FileSystemXmlApplicationContext(configLocation);
10         UserBean u = (UserBean) context.getBean("user");
11         System.out.println(u.getName());
12     }
13 }

构造器注入

在类被实例化时,它的构造方法被调用并且只能调用一次。所以构造器常被用于类的初始化操作。<constructor-arg>是<bean>元素的子元素。通过<constructor-arg>元素的<value>子元素可以为构造方法传参。

通过Spring的构造器注入为用户JavaBean的属性赋值。

1)在用户UserBean中创建构造方法

 1 public class UserBean {
 2     private String name;
 3     private Integer age;
 4     
 5     public UserBean() {
 6         super();
 7     }
 8     
 9     public UserBean(String name, Integer age) {
10         this.name = name;
11         this.age = age;
12     }
13 
14     public String getName() {
15         return name;
16     }
17     public void setName(String name) {
18         this.name = name;
19     }
20     public Integer getAge() {
21         return age;
22     }
23     public void setAge(Integer age) {
24         this.age = age;
25     }
26 }

2)在Spring的配置文件test.xml中通过<constructor-arg>配置UserBean

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"  
 3     xmlns:mvc="http://www.springframework.org/schema/mvc"  
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 5     xmlns:p="http://www.springframework.org/schema/p"  
 6     xmlns:context="http://www.springframework.org/schema/context"  
 7     xmlns:aop="http://www.springframework.org/schema/aop" 
 8     xmlns:tx="http://www.springframework.org/schema/tx" 
 9     xsi:schemaLocation="   
10            http://www.springframework.org/schema/beans   
11            http://www.springframework.org/schema/beans/spring-beans.xsd   
12            http://www.springframework.org/schema/context   
13            http://www.springframework.org/schema/context/spring-context.xsd  
14            http://www.springframework.org/schema/mvc   
15            http://www.springframework.org/schema/mvc/spring-mvc.xsd
16            http://www.springframework.org/schema/aop 
17            http://www.springframework.org/schema/aop/spring-aop.xsd
18            http://www.springframework.org/schema/tx 
19            http://www.springframework.org/schema/tx/spring-tx.xsd
20            ">                 
21      <bean id="user" class="com.zhwy.misp.bean.UserBean">
22          <constructor-arg name="name" value="tomcat"></constructor-arg>
23          <constructor-arg name="age" value="16"></constructor-arg>
24      </bean>
25  </beans>

3)测试类Test

 1 import org.springframework.context.ApplicationContext;
 2 import org.springframework.context.support.FileSystemXmlApplicationContext;
 3 import com.zhwy.misp.bean.UserBean;
 4 
 5 public class Test {
 6     public static void main(String[] agrs) {
 7         String name = "test.xml";
 8         String configLocation = ClassLoader.getSystemResource(name).getPath();
 9         ApplicationContext context = new FileSystemXmlApplicationContext(configLocation);
10         UserBean u = (UserBean) context.getBean("user");
11         System.out.println(u.getName());
12     }
13 }
原文地址:https://www.cnblogs.com/aaron911/p/7594978.html