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

来源:互联网 发布:淘宝装修免费一键安装 编辑:程序博客网 时间:2024/05/22 13:34

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和服务层进行解耦,后面会介绍更加简单的注解方式注入。

0 0
原创粉丝点击