前言
控制反轉(zhuǎn)(ioc)用來解決耦合的,主要分為兩種類型:依賴注入和依賴查找。
依賴注入就是把本來應(yīng)該在程序中有的依賴在外部注入到程序之中,當(dāng)然他也是設(shè)計(jì)模式的一種思想。
假定有接口a和a的實(shí)現(xiàn)b,那么就會(huì)執(zhí)行這一段代碼a a=new b();這個(gè)時(shí)候必然會(huì)產(chǎn)生一定的依賴,然而出現(xiàn)接口的就是為了解決依賴的,但是這么做還是會(huì)產(chǎn)生耦合,我們就可以使用依賴注入的方式來實(shí)現(xiàn)解耦。在ioc中可以將要依賴的代碼放到xml中,通過一個(gè)容器在需要的時(shí)候把這個(gè)依賴關(guān)系形成,即把需要的接口實(shí)現(xiàn)注入到需要它的類中,這可能就是“依賴注入”說法的來源了。
簡(jiǎn)單的理解依賴注入
那么我們現(xiàn)在拋開spring,拋開xml這些相關(guān)技術(shù),怎么使用最簡(jiǎn)單的方式實(shí)現(xiàn)一個(gè)依賴注入呢?現(xiàn)在還是接口a和a的實(shí)現(xiàn)b。
那么我們的目的是這樣的,a a=new b();現(xiàn)在我們?cè)诙x一個(gè)類c,下面就是c和a的關(guān)系,c為了new出一個(gè)a接口的實(shí)現(xiàn)類
1
2
3
4
5
6
|
public class c { private a a; public c(a a) { this .a=a; } } |
那么如何去new呢,定義一個(gè)類d,在d中調(diào)用c的構(gòu)造方法的時(shí)候new b();即
1
2
3
4
5
6
|
public class d{ @test public void use(){ c c= new c( new b()); } } |
這樣我們?cè)赾中就不會(huì)產(chǎn)生a和b的依賴了,之后如果想改變a的實(shí)現(xiàn)類的話,直接可以修改d中的構(gòu)造方法的參數(shù)就可以了,很簡(jiǎn)單,也解決了耦合。這種方式就是最常說的構(gòu)造器注入。
那么spring就是解決耦合和使用ioc的,這里最簡(jiǎn)單的spring依賴注入的例子:
springconfig.xml
1
2
3
4
5
6
7
8
9
|
<?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> |
解析:這里配置了兩個(gè)bean,第一個(gè)是為了給構(gòu)造器中注入一個(gè)bean,第二個(gè)是構(gòu)造器中要注入的bean。
hello.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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
1
2
3
4
5
6
7
8
9
10
11
|
package smile; /** * created by smile on 2016/4/20. */ public class thetestinterface { private hello hello; public thetestinterface(hello hello) { this .hello = hello; } } |
use.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
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(); } } |
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對(duì)服務(wù)器之家的支持。
原文鏈接:http://www.cnblogs.com/Summer7C/p/5415887.html