Spring自动装配bean(Autowire)

本文介绍了Spring自动装配bean的功能,通过设置`<bean>`的`autowire`属性实现Bean之间的关联关系。以byName为例,当设置autowire为byName时,Spring会根据属性名自动查找并注入相同名字的Bean,省去了手动配置ref的步骤。测试结果显示,自动装配成功完成了Bean的注入。

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

Spring自动装配bean(Autowire)

自动装配就是指 Spring 容器可以自动装配(autowire)相互协作的 Bean 之间的关联关系,将一个 Bean 注入其他 Bean 的 Property 中。

要使用自动装配,就需要配置 元素的 autowire 属性。autowire 属性有五个值

名称说明
byName根据 Property 的 name 自动装配,如果一个 Bean 的 name 和另一个 Bean 中的 Property 的 name 相同,则自动装配这个 Bean 到 Property 中。
byType根据 Property 的数据类型(Type)自动装配,如果一个 Bean 的数据类型兼容另一个 Bean 中 Property 的数据类型,则自动装配。
constructor根据构造方法的参数的数据类型,进行 byType 模式的自动装配。
autodetect如果发现默认的构造方法,则用 constructor 模式,否则用 byType 模式。
no默认情况下,不使用自动装配,Bean 依赖必须通过 ref 元素定义。

下面是通过修改 《Spring注入依赖(注解方式)https://blog.youkuaiyun.com/qq_51372098/article/details/116744580》中案例演示如何实现自动装配。首先将spring.xml配置文件修改成自动装配模式,如下所示:

<?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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="personDao" class="com.ljt.spring.PersonDaoImpl" />
    <bean id="personService" class="com.ljt.spring.PersonServiceImpl"
          autowire="byName" />
    <bean id="personController" class="com.ljt.spring.PersonController"
          autowire="byName" />
</beans>

用于配置 personService 和 personController 的 bean元素中除了 id 和 class 属性以外,还增加了 autowire 属性,并将其属性值设置为 byName(按属性名称自动装配)。

默认情况下,配置文件中需要通过 ref 装配 Bean,但设置了 autowire=“byName”,Spring 会在配置文件中自动寻找与属性名字 personDao 相同的 bean,找到后,通过调用setPersonDao(PersonDao personDao)方法将 id 为 personDao 的 Bean 注入 id 为 personService 的 Bean 中,这时就不需要通过 ref 装配了。

使用 JUnit 再次运行测试类中的 test() 方法, 测试结果如下所示:

Dao层的add()方法执行了
Service层的add()方法执行了
Controller层的add()方法执行了

使用自动装配的方式同样可以完成注入。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值