Spring依赖注入的几种方式(XML配置)

注:不想看具体代码的话,可以直接看文末总结。

环境

  • Ubuntu 22.04
  • IntelliJ IDEA 2022.1.3
  • JDK 17.0.3
  • Spring 5.3.21

准备

创建Maven项目 test0706

修改 pom.xml 文件,添加依赖:

        ......
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.21</version>
        </dependency>
        ......

src/main/resources 目录下创建 applicationContext.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

</beans>

src/test/java 目录下创建测试:

public class Test0706 {

}

设值注入

创建如下POJO:

  • Axe :Axe接口;
  • StoneAxe :Axe实现类;
  • SteelAxe :Axe实现类;
  • Person :Person持有Axe;
package pojo;

public interface Axe {
    public void chop();
}
package pojo;

public class StoneAxe implements Axe{
    public StoneAxe() {
        System.out.println("StoneAxe constructor");
    }

    @Override
    public void chop() {
        System.out.println("Stone axe!");
    }
}
package pojo;

public class SteelAxe implements Axe{
    public SteelAxe() {
        System.out.println("SteelAxe constructor");
    }

    @Override
    public void chop() {
        System.out.println("Steel axe!");
    }
}
package pojo;

public class Person {
    private String name;
    private Axe axe;

    public void setAxe(Axe axe) {
        this.axe = axe;
    }

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

    public void useAxe() {
        System.out.println("I am " + name);
        axe.chop();
    }

    public Person() {
        System.out.println("Person constructor");
    }
}

applicationContext.xml 中注册bean:

    ......
    <bean id="stoneAxe" class="pojo.StoneAxe"/>

    <bean id="steelAxe" class="pojo.SteelAxe"/>

    <bean id="person" class="pojo.Person">
        <property name="name" value="Tom"/>
        <property name="axe" ref="stoneAxe"/>
    </bean>
    ......

创建测试用例:

    @Test
    public void test1() {
        var ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

        System.out.println("before getBean");

        var person = ctx.getBean("person", Person.class);

        person.useAxe();
    }

运行测试,如下:

StoneAxe constructor
SteelAxe constructor
Person constructor
before getBean
I am Tom
Stone axe!

总结:

  • 一般的bean(相对工厂bean)是在Spring初始化时创建的(注意:默认的scope是 singleton ,如果是 prototype ,则是在每次 getBean() 的时候创建实例对象);
  • 可以直接注入值( value ),也可以注入bean( ref );
  • 被注入的bean(如本例中的 stoneAxe )在 Person 之前实例化;
  • 具体如何注入呢?是通过反射来调用Person的setter方法,其中方法名是字符串拼起来的,具体来讲是 set 加上首字母大写的 属性名 。本例中, person 有一个属性叫做 axe ,则Spring会拼出 setAxe() 方法,并把 ref 的对象作为参数传进去。所以,一定要确保Person有对应的方法;

构造注入

构造注入和设值注入非常相像,二者的主要区别为:

  • 设值注入是通过setter方法来注入被依赖对象;
  • 构造注入是通过构造方法来注入被依赖对象;

创建如下POJO:

  • Book :Book接口;
  • PlayBook :Book实现类;
  • StudyBook :Book实现类;
  • Student :Student持有Book;
package pojo;

public interface Book {
    public void show();
}
package pojo;

public class PlayBook implements Book{
    public PlayBook() {
        System.out.println("PlayBook constructor");
    }
    
    @Override
    public void show() {
        System.out.println("Play book!");
    }
}
package pojo;

public class StudyBook implements Book{
    public StudyBook() {
        System.out.println("StudyBook constructor");
    }

    @Override
    public void show() {
        System.out.println("Study book!");
    }
}
package pojo;

public class Student {
    private String name;
    private Book book;

    public Student(String name, Book book) {
        System.out.println("Student constructor");

        this.name = name;
        this.book = book;
    }

    public void readBook() {
        System.out.println("I am " + name);
        book.show();
    }
}

applicationContext.xml 中注册bean:

    ......
    <bean id="playBook" class="pojo.PlayBook"/>

    <bean id="studyBook" class="pojo.StudyBook"/>

    <bean id="student" class="pojo.Student">
        <constructor-arg index="0" value="Jerry"/>
        <constructor-arg index="1" ref="playBook"/>
    </bean>
    ......

创建测试用例:

    @Test
    public void test2() {
        var ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

        System.out.println("before getBean");

        var student = ctx.getBean("student", Student.class);

        student.readBook();
    }

运行测试,如下:

......
PlayBook constructor
StudyBook constructor
Student constructor
before getBean
I am Jerry
Play book!

总结:

  • 一般的bean(相对工厂bean)是在Spring初始化时创建的(注意:默认的scope是 singleton ,如果是 prototype ,则是在每次 getBean() 的时候创建实例对象);
  • 可以直接注入值( value ),也可以注入bean( ref );
  • 被注入的bean(如本例中的 PlayBook )在 Student 之前实例化;
  • 具体如何注入呢?是通过反射来调用bean的构造方法,如果有多个参数,可以用 index 来区分(下标从 0 开始),所以一定要确保有对应的构造方法;

接口注入

接口注入和设值注入也很相像,都是通过setter方法来注入被依赖对象,二者的主要区别为:

  • 接口注入需要实现特定接口,因此setter方法是固定的;
  • 在设值注入中,被注入的具体对象是我们自己定的,而在接口注入中,被注入的对象是Spring决定的,我们不需要配置 <property> 来注入对象;

ApplicationContextAware 接口为例,在Spring初始化时,会扫描所有的bean,如果发现某个bean实现了该接口,就会自动调用其 setApplicationContext() 方法,把Spring容器本身传进去;

创建POJO MyBean

package pojo;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class MyBean implements ApplicationContextAware {
    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("before setter");

        this.applicationContext = applicationContext;
    }

    public void foo() {
        System.out.println(applicationContext.getDisplayName());
    }
}

applicationContext.xml 中注册bean:

    ......
    <bean id="myBean" class="pojo.MyBean"/>
    ......

创建测试用例:

    @Test
    public void test3() {
        var ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

        System.out.println("before getBean");

        var myBean = ctx.getBean("myBean", MyBean.class);

        myBean.foo();
    }

运行测试,如下:

......
before setter
before getBean
org.springframework.context.support.ClassPathXmlApplicationContext@506e6d5e

总结:

  • 无需配置注入对象;
  • 具体如何注入呢?Spring会扫描所有的bean,如果发现某个bean实现了某些接口,就会自动调用其接口方法,把特定对象(比如Spring容器本身)传进去;

自动装配

对于bean之间的依赖关系,通常我们使用 ref 来显式指定被注入的对象。Spring也支持自动装配(autowire)。

常见的自动装配策略有:

  • byName :通过setter方法名来查找bean ID,跟前面说的通过bean ID来调用setter方法正好相反。具体操作为:去掉 set 前缀,然后首字母小写。比如 setName() 方法,得到的bean ID是 name 。如果找不到对应的bean ID,则不进行注入操作。由于ID是唯一的,所以不存在找到多个bean的情况;
  • byType :根据setter方法的参数类型来查找bean,如果找不到符合的bean,则不进行注入操作。如果找到多个符合的bean,则抛出异常;

创建如下POJO:

  • Ball:Ball接口;
  • FootBall :Ball实现类;
  • BasketBall :Ball实现类;
  • Athlete :Athlete持有Ball;
package pojo;

public interface Ball {
    public void fly();
}
package pojo;

public class FootBall implements Ball{
    @Override
    public void fly() {
        System.out.println("FootBall is flying");
    }
}
package pojo;

public class BasketBall implements Ball{
    @Override
    public void fly() {
        System.out.println("BasketBall is flying");
    }
}
package pojo;

public class Athlete {
    private Ball ball;

    public void setBall(Ball ball) {
        this.ball = ball;
    }

    public void play() {
        ball.fly();
    }
}

applicationContext.xml 中注册bean:

    ......
    <bean id="footBall" class="pojo.FootBall"/>

    <bean id="basketBall" class="pojo.BasketBall"/>

    <bean id="athlete" class="pojo.Athlete" autowire="byName"/>
    ......

创建测试用例:

    @Test
    public void test4() {
        var ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

        var athlete = ctx.getBean("athlete", Athlete.class);

        athlete.play();
    }

运行测试,如下:

java.lang.NullPointerException: Cannot invoke "pojo.Ball.fly()" because "this.ball" is null

这是因为 autowire="byName" ,setter方法为 setBall() 。移除 set 前缀,并把首字母 B 变成 b ,所以会查找ID为 ball 的bean,但是没有找到,所以不会注入对象。但是后面调用了Ball的 fly() 方法,所以报了空指针错误。

修改配置如下:

    ......
    <bean id="ball" class="pojo.FootBall"/>

    <bean id="basketBall" class="pojo.BasketBall"/>

    <bean id="athlete" class="pojo.Athlete" autowire="byName"/>
    ......

再次运行测试,这次成功了:

FootBall is flying

修改配置,把 byName 改为 byType

    ......
    <bean id="athlete" class="pojo.Athlete" autowire="byType"/>
    ......

再次运行测试,如下:

org.springframework.beans.factory.UnsatisfiedDependencyException: 
Error creating bean with name 'athlete' defined in class path resource [applicationContext.xml]: 
Unsatisfied dependency expressed through bean property 'ball'; 
nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: 
No qualifying bean of type 'pojo.Ball' available: 
expected single matching bean but found 2: ball,basketBall

找到了多个符合的bean,所以报错了。

修改配置,只保留一个Ball的实现类:

    ......
<!--    <bean id="ball" class="pojo.FootBall"/>-->

    <bean id="basketBall" class="pojo.BasketBall"/>

    <bean id="athlete" class="pojo.Athlete" autowire="byType"/>
    ......

再次运行测试,这次成功了。

BasketBall is flying

总结

  • Bean默认的scope是 singleton ,表示在Spring初始化的时候创建,如果设置为 prototype ,则是在每次 getBean() 的时候创建实例对象(注:工厂bean创建bean行为有所不同,即使是singleton,也不是在Spring初始化时创建,而是在第一次 getBean() 时创建,参见我另一篇文档)。
  • 可以直接注入值( value ),也可以注入bean( ref );
  • 被注入的bean(如本例中的 stoneAxe )在 Person 之前实例化;
  • 具体如何注入呢?
    • 设值注入:通过反射来调用bean的setter方法,其中方法名是字符串拼起来的,具体来讲是 set 加上首字母大写的 属性名 。所以,一定要确保bean有对应的方法;
    • 构造注入:通过反射来调用bean的构造方法,如果有多个参数,可以用 index 来区分(下标从 0 开始),所以一定要确保有对应的构造方法;
    • 接口注入:无需配置注入对象。Spring会扫描所有的bean,如果发现某个bean实现了某些接口,就会自动调用其接口方法,把特定对象(比如Spring容器本身)传进去;
  • 自动装配
    • byName :通过setter方法名来查找bean ID,跟前面说的通过bean ID来调用setter方法正好相反。把setter方法名去掉 set 前缀,然后首字母小写。比如对于 setName() 方法,得到的bean ID是 name
      • 如果找不到对应的bean ID,则不进行注入操作;
      • 如果找到对应的bean ID,则进行注入操作;
      • 由于ID是唯一的,所以不存在找到多个bean ID的情况;
    • byType :根据setter方法的参数类型来查找bean:
      • 如果找不到符合的bean,则不进行注入操作;
      • 如果找到唯一符合的bean,则进行注入操作;
      • 如果找到多个符合的bean,则抛出异常;

关于通过Spring注解来管理注入,参见 https://blog.csdn.net/duke_ding2/article/details/126570338

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值