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

本文介绍了Spring框架中依赖注入的基本概念及实现方式,包括构造器注入和setter方法注入,并提供了具体的代码示例。同时展示了如何通过XML配置文件进行依赖注入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值