java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Spring依赖注入

Spring依赖注入的几种方式分享梳理总结

作者:蓝黑2020

这篇文章主要介绍了Spring依赖注入的几种方式分享梳理总结,文章围绕主题展开详细,具有一定参考价值,需要的朋友可以参考一下

环境

准备

创建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:

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!

总结:

构造注入

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

创建如下POJO:

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!

总结:

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

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

总结:

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

常见的自动装配策略有:

创建如下POJO:

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

总结

具体如何注入呢?

自动装配 :

byName :通过setter方法名来查找bean ID,跟前面说的通过bean ID来调用setter方法正好相反。把setter方法名去掉 set 前缀,然后首字母小写。比如对于 setName() 方法,得到的bean ID是 name

byType :根据setter方法的参数类型来查找bean:

到此这篇关于Spring依赖注入的几种方式分享梳理总结的文章就介绍到这了,更多相关Spring依赖注入内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文