Spring自动组装的方式设置bean之间的依赖关系

本文介绍了Spring框架中自动装配的两种主要方式:byType和byName。byType根据类型自动匹配bean,而byName则根据bean的ID进行匹配。这两种方式简化了依赖注入的过程,但可能降低配置文件的可读性。

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

就是在beans标签里面加上一个default-autowire的属性取值有byType,byName,constructor,default,no常用就是byType和byName

1.根据类型自动组装。

<?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.xsd"
default-autowire="byType">

<bean id="userdao" class="chp1.ex1.dao.UserDAO"></bean>
<bean id="userserv" class="chp1.ex1.service.UserService">	 
</bean>
</beans>

byType就是根据类型自动组装,在beans里设置了以后就不需要在bean标签里面设置property属性了,运行程序的时候Spring框架会根据Action里属性的类型自动创建一个该类型的对象,Service里的Dao对象也是如此创建。


2.根据名字自动组装

<?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.xsd"
default-autowire="byName">

<bean id="userdao" class="chp1.ex1.dao.UserDAO"></bean>
<bean id="userserv" class="chp1.ex1.service.UserService">	 
</bean>
</beans>
byName就是根据名字自动组装,运行程序的时候Spring框架会根据Action里属性名去配置文件里找id为这个名的类,并创建该类的对象。

这里只介绍这两种常用的,虽然这两种比较常用,但是还是不推荐这样写,因为这样写,在配置文件里看不出各个类的依赖关系,可读性差。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值