简单的理解依赖注入

控制反转(IoC)用来解决耦合的,主要分为两种类型:依赖注入和依赖查找。

依赖注入就是把本来应该在程序中有的依赖在外部注入到程序之中,当然他也是设计模式的一种思想。

假定有接口A和A的实现B,那么就会执行这一段代码A a=new B();这个时候必然会产生一定的依赖,然而出现接口的就是为了解决依赖的,但是这么做还是会产生耦合,我们就可以使用依赖注入的方式来实现解耦。在Ioc中可以将要依赖的代码放到XML中,通过一个容器在需要的时候把这个依赖关系形成,即把需要的接口实现注入到需要它的类中,这可能就是“依赖注入”说法的来源了。

那么我们现在抛开Spring,抛开XML这些相关技术,怎么使用最简单的方式实现一个依赖注入呢?现在还是接口A和A的实现B。

那么我们的目的是这样的,A a=new B();现在我们在定义一个类C,下面就是C和A的关系,C为了new出一个A接口的实现类

1 public class C {
2     private A a;
3     public C(A a) {
4         this.a=a;
5     }
6 }

那么如何去new呢,定义一个类D,在D中调用C的构造方法的时候new B();即

1 public class D{
2     @Test
3     public void Use(){
4         C c=new C(new B());
5     }
6 }

这样我们在C中就不会产生A和B的依赖了,之后如果想改变A的实现类的话,直接可以修改D中的构造方法的参数就可以了,很简单,也解决了耦合。这种方式就是最常说的构造器注入。

那么Spring就是解决耦合和使用Ioc的,这里最简单的Spring依赖注入的例子:

SpringConfig.xml

1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
5     <bean id="sayhello" class="smile.TheTestInterface">
6         <constructor-arg ref="hello"/>
7     </bean>
8     <bean id="hello" class="smile.Hello" />
9 </beans>

解析:这里配置了两个Bean,第一个是为了给构造器中注入一个Bean,第二个是构造器中要注入的Bean。

Hello.java

 1 package smile;
 2 
 3 
 4 
 5 /**
 6  * Created by smile on 2016/4/21.
 7  */
 8 public class Hello {
 9     public Hello(){
10         System.out.println("Hello");
11     }
12 
13     public void sayHello(){
14         System.out.println("I want say Hello");
15     }
16 }

TheInterface.java

 1 package smile;
 2 
 3 /**
 4  * Created by smile on 2016/4/20.
 5  */
 6 public class TheTestInterface {
 7     private Hello hello;
 8     public TheTestInterface(Hello hello) {
 9         this.hello = hello;
10     }
11 }

Use.java

 1 package com.smile;
 2 
 3 import org.junit.Test;
 4 import org.springframework.context.ApplicationContext;
 5 import org.springframework.context.support.ClassPathXmlApplicationContext;
 6 import smile.Hello;
 7 
 8 /**
 9  * Created by smile on 2016/4/21.
10  */
11 public class Use {
12     @Test
13     public void UseTest(){
14         ApplicationContext context=new ClassPathXmlApplicationContext("SpringConfig.xml");
15         Hello hello=(Hello)context.getBean("hello");
16         hello.sayHello();
17     }
18 }

---恢复内容结束---

原文地址:https://www.cnblogs.com/Summer7C/p/5415887.html