Spring中Bean对象的自动注入机制

本文介绍了Spring中Bean对象的自动注入机制,包括通过autowire='byName'按名称注入,autowire='byType'按类型注入,以及autowire='constructor'构造器注入。byName依赖于成员变量名,byType则依据变量类型,而构造器注入虽然能精确匹配,但使用较少,因为可能导致阅读困扰。

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

使用autowire标签完成bean的自动注入

首先,我们有如下两个类:

public class Student{
	private String name;
	private Book book;
	//set and get methods
}

class Book{
	private int ID;
	//set and get methods
}

autowire=“byName”,根据成员变量名字进行注入

<?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">
    <!--配置业务层的对象-->

    <!--通过指定autowire的方式,我们不需要再去为book指明对象信息,但是额外的bean的ID要与类中的变量名称相同,此处为book-->
    <bean id="student" class="com.erwin.entity.Student" autowire="byName">
        <property name="name" value="Erwin"></property>
    </bean>

    <!--student会自动找到下面这个bean对象,因为它的ID与Student类中相关变量的名称相同-->
    <bean id="book" class="com.erwin.entity.Book">

        <property name="ID" value="001"></property>

    </bean>
</beans>

autowire=“byType”, 根据变量的类型自动注入

使用这种方式,必须保证当前xml中有且只有一个对应类的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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--配置业务层的对象-->

    <!--通过指定autowire的方式,我们不需要再去为book指明对象信息,但是额外的bean的类型要在当前xml中存在,此处为Book类-->
    <bean id="student" class="com.erwin.entity.Student" autowire="byName">
        <property name="name" value="Erwin"></property>
    </bean>

    <!--student会自动找到下面这个bean对象,因为它的类与Student类中相关变量(book)对应的Book类相同,而无所谓它叫什么名字-->
    <bean id="bookkkkkk" class="com.erwin.entity.Book">

        <property name="ID" value="001"></property>

    </bean>
</beans>

autowire="constructor"构造器方式自动注入

该方法事实上调用了内部对应的有参构造器,写起来很麻烦,很少使用,而且很容易造成阅读上的困惑。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值