天天看點

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 public SpringAutowiredHelloAction(HelloServiceImpl helloservice){ this.helloservice = helloservice; } setter方法自動注入: /* @Autowired public void setHelloservice(HelloService helloservice) { this.helloservice = helloservice; } 最後在spring的reference文檔中有提到,如果不使用自動注入,盡量使用setter方法,一般通用的也是使用setter方法。 而使用自動注入還是配置檔案方式,如果jdk低于1.5或者spring不是2.5,就隻能夠使用配置檔案方式了。其它的就看實際項目選擇了。