1. 程式人生 > >Spring Ioc 之二 -依賴注入的幾種方式

Spring Ioc 之二 -依賴注入的幾種方式

一 setter方法注入 上一篇中Spring版HelloWorld中,helloaction注入helloservice是採用了setter方法。 配置檔案如下:

action實現類中程式碼: private IHelloService helloservice; private String name ; public void sayHello(){ helloservice.sayHello(); System.out.println(this.name); } public void setHelloservice(IHelloService helloservice) { this.helloservice = helloservice; } public void setName(String name) { this.name = name; } 這裡的name和helloservice都採用屬性的setter方法注入。即類中設定一個全域性屬性,並對屬性有setter方法,以供容器注入。 二 構造器注入 spring也支援構造器注入,也即有些資料中的構造子或者建構函式注入。 先看配置檔案:

action實現類中程式碼: private HelloServiceImpl helloservice; private String name ; public SpringConstructorHelloAction(HelloServiceImpl helloservice,String name){ this.helloservice = helloservice; this.name = name ; } @Override public void sayHello() { helloservice.sayHello(); System.out.println(this.name); } 同樣設定2個屬性,然後在建構函式中注入。 三靜態工廠注入 配置檔案如下:

action實現類: private HelloServiceImpl helloservice; private String name = null; private SpringFactoryHelloAction(String name ,HelloServiceImpl helloservice){ this.helloservice = helloservice ; this.name = name ; } public static SpringFactoryHelloAction createInstance(String name ,HelloServiceImpl helloservice) { SpringFactoryHelloAction fha = new SpringFactoryHelloAction (name,helloservice); // some other operations return fha; } @Override public void sayHello() { helloservice.sayHello(); System.out.println(this.name); } 四 無配置檔案注入(自動注入) 上面三種方法都需要編寫配置檔案,在spring2.5中還提供了不編寫配置檔案的ioc實現。需要注意的是,無配置檔案指bean之間依賴,不基於配置檔案,而不是指沒有spring配置檔案。 配置檔案如下:

可見上面只是設定了helloService和helloAction兩個bean,並沒有設定helloAction對helloService的依賴。 另外是必須的,有此才支援自動注入。 action實現類: /* * 屬性自動裝載 */ /* @Autowired private HelloService helloservice; @Override public void sayHello() { helloservice.sayHello(); 。上面程式碼很簡單,在屬性上加上 @Autowired註釋,spring會自動注入HelloService 。 同樣也支援構造器和setteer方法的注入,如下: 構造器自動注入: /* * 還可以使用建構函式設定 */ @Autowired public SpringAutowiredHelloAction(HelloServiceImpl helloservice){ this.helloservice = helloservice; } setter方法自動注入: /* * 也可以使用set方法設定 */ /* @Autowired public void setHelloservice(HelloService helloservice) { this.helloservice = helloservice; } 最後在spring的reference文件中有提到,如果不使用自動注入,儘量使用setter方法,一般通用的也是使用setter方法。 而使用自動注入還是配置檔案方式,如果jdk低於1.5或者spring不是2.5,就只能夠使用配置檔案方式了。其它的就看實際專案選擇了。