温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Spring依赖注入的方式有哪些

发布时间:2022-07-13 14:20:22 来源:亿速云 阅读:94 作者:iii 栏目:开发技术

这篇文章主要介绍“Spring依赖注入的方式有哪些”,在日常操作中,相信很多人在Spring依赖注入的方式有哪些问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Spring依赖注入的方式有哪些”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

环境

  • 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="byName"/>
    ......

再次运行测试,如下:

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依赖注入的方式有哪些”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI