【Spring】spring两种依赖注入方式:constructor & setter

spring中依赖注入有两种方式:
1.通过构造函数注入
2.通过setter方法注入

1.通过构造函数注入

spring通过调用需要进行依赖注入的类的构造方法来完成依赖注入,我们需要写好构造方法,以及配置好构造方法中的参数。
举例
向PersonServiceImpl中注入PersonDao,可采用以下配置:

<?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:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
    <!-- 由 Spring容器创建该类的实例对象 -->
    <bean id="personDaoImpl" class="com.sp.PersonDaoImpl"></bean>
    <bean id="personServiceImpl" class="com.sp.PersonServiceImpl">
    	<constructor-arg ref="personDaoImpl"></constructor-arg>
    </bean>
</beans>

constructor-arg元素中便是对构造函数的参数的配置,我们可以通过构造方法中的参数的索引值来确定是哪个constructor-arg元素对应哪个参数,使用index属性在元素中进行配置。也可以直接使用ref来引用其它bean,spring会根据引用的类型与参数进行匹配。

2.通过setter方法注入

依赖方要提供被依赖方的setter方法,并且要在配置文件中进行配置。与1中不同的是使用的为property标签,每一个property元素对应一个实现了setter方法的类属性。并且通过依赖类中被依赖类的对象名来确定。

<?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:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
    <!-- 由 Spring容器创建该类的实例对象 -->
    <bean id="personDaoImpl" class="com.sp.PersonDaoImpl"></bean>
    <bean id="personServiceImpl" class="com.sp.PersonServiceImpl">
    	<property name="personDao" ref="personDaoImpl"></property>
    </bean>
</beans>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值