您的位置:首页 > 其它

依赖注入的方式和注入的配置实例

2016-03-24 14:49 330 查看
Spring容器是一个IOC容器,通过反转拿到对象然后使用依赖注入到目标组件,下面使用依赖注入,把daobean注入到servicebean的来年各种方式:

首先看一下基本类型对象的注入:

1.使用构造器注入

public class PersonServiceBean implements PersonService{
private PersonDao personDao; // 接口

public PersonServiceBean(PersonDao personDao) {
this.personDao = personDao;
}

public void save() {
personDao.add();
}
}


2.使用setter方法注入

public class PersonServiceBean implements PersonService{
private PersonDao personDao;

public void setPersonDaoBean(PersonDao personDao) {
this.personDao = personDao;
}

public void save() {
personDao.add();// 接口的add方法,不关心谁实现了这个接口
}
}


注入XML配置:

1.配置属性注入其他bean

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <bean id="personDao" class="com.heying.dao.impl.PersonDaoBean"></bean>
<bean id="personService" class="com.heying.service.PersonServiceBean">
<property name="personDao" ref="personDao"></property>
<!-- 注入的属性,注入值(注入的名称,spring会按照这个名称在容器里面寻找相应的bean,[已经配置在上面]) -->
</bean>
</beans>




2.使用内部bean注入其他bean

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <!-- <bean id="personDao" class="com.heying.dao.impl.PersonDaoBean"></bean>  -->
<bean id="personService" class="com.heying.service.PersonServiceBean">
<property name="personDao">
<bean class="com.heying.dao.impl.PersonDaoBean"></bean>
</property>
</bean>
</beans>




无论是采用何种方式注入属性,何种方式注入其他的bean 都是为了业务bean和服务层进行解耦,后面会介绍更加简单的注解方式注入。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  依赖注入