Spring 2.5 IOC,依赖注入 原理分析 :
1,构造器注入
2,属性setter注入
传统的对象实例化是由应用本身来做的,依赖注入就是在运行期,由外部容器动态地将将依赖对象注入到组件中,
setter注入代码例子:
----------------------------------------
首先我们定义DAO层接口:
然后实现这个接口:
定义service接口
实现:
配置文件:
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>