控制反轉(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 }
---恢復內容結束---
