欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring依賴注入的幾種方式分享梳理總結(jié)

 更新時間:2022年07月08日 16:02:25   作者:藍(lán)黑2020  
這篇文章主要介紹了Spring依賴注入的幾種方式分享梳理總結(jié),文章圍繞主題展開詳細(xì),具有一定參考價值,需要的朋友可以參考一下

環(huán)境

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

準(zhǔn)備

創(chuàng)建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 目錄下創(chuàng)建 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 目錄下創(chuàng)建測試:

public class Test0706 {
}

設(shè)值注入

創(chuàng)建如下POJO:

  • Axe :Axe接口;
  • StoneAxe :Axe實現(xiàn)類;
  • SteelAxe :Axe實現(xiàn)類;
  • 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>
    ......

創(chuàng)建測試用例:

    @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!

總結(jié):

  • 一般的bean(相對工廠bean)是在Spring初始化時創(chuàng)建的(注意:默認(rèn)的scope是 singleton ,如果是 prototype ,則是在每次 getBean() 的時候創(chuàng)建實例對象);
  • 可以直接注入值( value ),也可以注入bean( ref );
  • 被注入的bean(如本例中的 stoneAxe )在 Person 之前實例化;
  • 具體如何注入呢?是通過反射來調(diào)用Person的setter方法,其中方法名是字符串拼起來的,具體來講是 set 加上首字母大寫的 屬性名 。本例中, person 有一個屬性叫做 axe ,則Spring會拼出 setAxe() 方法,并把 ref 的對象作為參數(shù)傳進去。所以,一定要確保Person有對應(yīng)的方法;

構(gòu)造注入

構(gòu)造注入和設(shè)值注入非常相像,二者的主要區(qū)別為:

  • 設(shè)值注入是通過setter方法來注入被依賴對象;
  • 構(gòu)造注入是通過構(gòu)造方法來注入被依賴對象;

創(chuàng)建如下POJO:

  • Book :Book接口;
  • PlayBook :Book實現(xiàn)類;
  • StudyBook :Book實現(xiàn)類;
  • 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>
    ......

創(chuàng)建測試用例:

    @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!

總結(jié):

  • 一般的bean(相對工廠bean)是在Spring初始化時創(chuàng)建的(注意:默認(rèn)的scope是 singleton ,如果是 prototype ,則是在每次 getBean() 的時候創(chuàng)建實例對象);
  • 可以直接注入值( value ),也可以注入bean( ref );
  • 被注入的bean(如本例中的 PlayBook )在 Student 之前實例化;
  • 具體如何注入呢?是通過反射來調(diào)用bean的構(gòu)造方法,如果有多個參數(shù),可以用 index 來區(qū)分(下標(biāo)從 0 開始),所以一定要確保有對應(yīng)的構(gòu)造方法; 接口注入

接口注入和設(shè)值注入也很相像,都是通過setter方法來注入被依賴對象,二者的主要區(qū)別為:

  • 接口注入需要實現(xiàn)特定接口,因此setter方法是固定的;
  • 在設(shè)值注入中,被注入的具體對象是我們自己定的,而在接口注入中,被注入的對象是Spring決定的,我們不需要配置 <property> 來注入對象;

ApplicationContextAware 接口為例,在Spring初始化時,會掃描所有的bean,如果發(fā)現(xiàn)某個bean實現(xiàn)了該接口,就會自動調(diào)用其 setApplicationContext() 方法,把Spring容器本身傳進去;

創(chuàng)建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"/>
    ......

創(chuàng)建測試用例:

    @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

總結(jié):

  • 無需配置注入對象;
  • 具體如何注入呢?Spring會掃描所有的bean,如果發(fā)現(xiàn)某個bean實現(xiàn)了某些接口,就會自動調(diào)用其接口方法,把特定對象(比如Spring容器本身)傳進去; 自動裝配

對于bean之前的依賴關(guān)系,通常我們使用 ref 來顯式指定被注入的對象。Spring也支持自動裝配(autowire)。

常見的自動裝配策略有:

  • byName :通過setter方法名來查找bean ID,跟前面說的通過bean ID來調(diào)用setter方法正好相反。具體操作為:去掉 set 前綴,然后首字母小寫。比如 setName() 方法,得到的bean ID是 name 。如果找不到對應(yīng)的bean ID,則不進行注入操作。由于ID是唯一的,所以不存在找到多個bean的情況;
  • byType :根據(jù)setter方法的參數(shù)類型來查找bean,如果找不到符合的bean,則不進行注入操作。如果找到多個符合的bean,則拋出異常;

創(chuàng)建如下POJO:

  • Ball:Ball接口;
  • FootBall :Ball實現(xiàn)類;
  • BasketBall :Ball實現(xiàn)類;
  • 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"/>
    ......

創(chuàng)建測試用例:

    @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,但是沒有找到,所以不會注入對象。但是后面調(diào)用了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的實現(xiàn)類:

    ......
<!--    <bean id="ball" class="pojo.FootBall"/>-->
    <bean id="basketBall" class="pojo.BasketBall"/>
    <bean id="athlete" class="pojo.Athlete" autowire="byType"/>
    ......

再次運行測試,這次成功了。

BasketBall is flying

總結(jié)

  • Bean默認(rèn)的scope是 singleton ,表示在Spring初始化的時候創(chuàng)建,如果設(shè)置為 prototype ,則是在每次 getBean() 的時候創(chuàng)建實例對象(注:工廠bean創(chuàng)建bean行為有所不同,即使是singleton,也不是在Spring初始化時創(chuàng)建,而是在第一次 getBean() 時創(chuàng)建,參見我另一篇文檔)。
  • 可以直接注入值( value ),也可以注入bean( ref );
  • 被注入的bean(如本例中的 stoneAxe )在 Person 之前實例化;

具體如何注入呢?

  • 設(shè)值注入:通過反射來調(diào)用bean的setter方法,其中方法名是字符串拼起來的,具體來講是 set 加上首字母大寫的 屬性名 。所以,一定要確保bean有對應(yīng)的方法;
  • 構(gòu)造注入:通過反射來調(diào)用bean的構(gòu)造方法,如果有多個參數(shù),可以用 index 來區(qū)分(下標(biāo)從 0 開始),所以一定要確保有對應(yīng)的構(gòu)造方法;
  • 接口注入:無需配置注入對象。Spring會掃描所有的bean,如果發(fā)現(xiàn)某個bean實現(xiàn)了某些接口,就會自動調(diào)用其接口方法,把特定對象(比如Spring容器本身)傳進去;

自動裝配 :

byName :通過setter方法名來查找bean ID,跟前面說的通過bean ID來調(diào)用setter方法正好相反。把setter方法名去掉 set 前綴,然后首字母小寫。比如對于 setName() 方法,得到的bean ID是 name

  • 如果找不到對應(yīng)的bean ID,則不進行注入操作;
  • 如果找到對應(yīng)的bean ID,則進行注入操作;
  • 由于ID是唯一的,所以不存在找到多個bean ID的情況;

byType :根據(jù)setter方法的參數(shù)類型來查找bean:

  • 如果找不到符合的bean,則不進行注入操作;
  • 如果找到唯一符合的bean,則進行注入操作;
  • 如果找到多個符合的bean,則拋出異常;

到此這篇關(guān)于Spring依賴注入的幾種方式分享梳理總結(jié)的文章就介紹到這了,更多相關(guān)Spring依賴注入內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論