spring依賴注入的方式

1.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方法,以供容器注入。 

2.構造器注入:

 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);

}

3.靜態工廠的注入:

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);

 }

4.無配置文件的注入

上面三種方法都需要編寫配置文件,在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,就只能夠使用配置文件方式了。其它的就看實際項目選擇了。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章