您的位置:首页 > 其它

简单的理解依赖注入

2016-04-21 10:17 381 查看
控制反转(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接口的实现类

public class C {
private A a;
public C(A a) {
this.a=a;
}
}


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

public class D{
@Test
public void Use(){
C c=new C(new B());
}
}


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

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

SpringConfig.xml

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


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

Hello.java

package smile;

/**
* Created by smile on 2016/4/21.
*/
public class Hello {
public Hello(){
System.out.println("Hello");
}

public void sayHello(){
System.out.println("I want say Hello");
}
}


TheInterface.java

package smile;

/**
* Created by smile on 2016/4/20.
*/
public class TheTestInterface {
private Hello hello;
public TheTestInterface(Hello hello) {
this.hello = hello;
}
}


Use.java

package com.smile;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import smile.Hello;

/**
* Created by smile on 2016/4/21.
*/
public class Use {
@Test
public void UseTest(){
ApplicationContext context=new ClassPathXmlApplicationContext("SpringConfig.xml");
Hello hello=(Hello)context.getBean("hello");
hello.sayHello();
}
}


---恢复内容结束---
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: