Spring自动装配 autowire

本文介绍了Spring框架中的自动装配特性,包括通过XML和注解两种方式实现。以一个实例展示了如何自动装配People类中的Cat和Dog属性,解释了byName和byType两种自动装配策略的工作原理。通过byName,Spring会根据setter方法名匹配bean的id,而byType则是根据类型匹配。手动装配作为对比,展示了配置文件中如何手动设置依赖。

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

什么是自动装配?

自动装配就是让应用程序上下文为你找出依赖项的过程。说的通俗一点,就是Spring会在上下文中自动查找,并自动给bean装配与其关联的属性!

spring中实现自动装配的方式有两种,一种是通过xml文件、另一种是通过注解。下面将为大家介绍这两种方式实现自动装配。

为了更简单的让大家理解,我们通过例子来说明:

有以下三个实体类,People类,Dog类,Cat类,分别代表人、狗、猫。人养了一只狗和一只猫,猫和狗都会叫。

public class Cat {
    public void shout(){
        System.out.println("miao~");
    }
}

public class Dog {
    public void shout(){
        System.out.println("wang wang~");
    }
}

public class Peopel {
    private Cat cat;
    private Dog dog;
    private String name;

    public Cat getCat() {
        return cat;
    }

    public void setCat(Cat cat) {
        this.cat = cat;
    }

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Peopel{" +
                "cat=" + cat +
                ", dog=" + dog +
                ", name='" + name + '\'' +
                '}';
    }
}

手动装配

讲自动装配之前,我们先来说一下手动装配,手动装配又是什么?手动装配就是手动的将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"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="cat" class="com.kuang.pojo.Cat"/>
    <bean id="dog" class="com.kuang.pojo.Dog"/>
    <bean id="people" class="com.kuang.pojo.Peopel">
        <property name="name" value="张三"/>
        <property name="cat" ref="cat"/>
        <property name="dog" ref="dog"/>
    </bean>
</beans>

方式一:通过xml文件实现自动装配
我们只需要在xml配置文件中的bean标签中加入一个属性autowire即可,例如:

<bean id="people" class="com.kuang.pojo.Peopel" autowire="byName">
        <property name="name" value="张三"/>
</bean>

使用autowire关键字声明bean的自动装配方式。其可选值为byName、byType、constructor,default,no;这里讲前边两个。

1.byName

设置autowire属性为byName,那么Spring会根据class属性找到实体类,然后查询实体类中所有setter方法的名字,根据setter方法后面的名字(例如SetDog,则setter方法后面的名字为dog)再到配置文件中寻找一个与该名字相同id的Bean,注入进来。如图:
在这里插入图片描述
在这里插入图片描述

参考 博客: https://www.cnblogs.com/bear7/p/12531016.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值