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,就只能够使用配置文件方式了。其它的就看实际项目选择了。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值