Spring2.5依赖注入的原理

本文介绍了Spring2.5框架中的IOC概念及其依赖注入的两种方式:构造器注入和属性setter注入,并通过示例代码详细展示了如何利用setter注入实现PersonService与PersonDao之间的依赖关系。
Spring 2.5 IOC,依赖注入 原理分析 :

1,构造器注入
2,属性setter注入
传统的对象实例化是由应用本身来做的,依赖注入就是在运行期,由外部容器动态地将将依赖对象注入到组件中,

setter注入代码例子:
----------------------------------------

首先我们定义DAO层接口:


public interface PersonDao{
//add person
public void add();
}


然后实现这个接口:
public class PersonDaoImpl implements PersonDao{
//实现add方法
public void add(){
//这是用于测试
System.out.println("添加Person成功");
}
}


定义service接口

public interface PersonService{

public void save();//保存Person对象

}


实现:

public class PersonServiceImpl{
private PersonDao personDao;//注入PersonDao对象
public void setPersonDao(PersonDao personDao){
this.personDao = personDao;
}

public PersonDao getPersonDao(){
return this.personDao;
}
}
public void save(){
personDao.add();
}
}

}


配置文件:

<?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-2.0.xsd">
<bean id="personDao" class="test.dao.impl.PersonDaoBean"/>
<bean id="personService" class="test.service.impl.PersonServiceBean">
<property name="personDao" ref="personDao">//这里引用上面的personDao
</property>
</bean>
</beans>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值