最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring使用@Autowired注解實現(xiàn)自動裝配方式

 更新時間:2021年09月27日 11:44:05   作者:想飛的魚Stitch  
這篇文章主要介紹了Spring使用@Autowired注解實現(xiàn)自動裝配方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

Spring支持注解配置

引入注解依賴

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">

啟用注解

<context:annotation-config/>

使用@Autowired注解實現(xiàn)自動裝配

1、IOC容器配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:context="http://www.springframework.org/schema/context"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd">
      <context:annotation-config/>
   <bean id="cat" class="indi.stitch.pojo.Cat"/>
   <bean id="dog" class="indi.stitch.pojo.Dog"/>
   <bean id="people" class="indi.stitch.pojo.People" />
</beans>

2、實體類使用@Autowired注解注入屬性

package indi.stitch.pojo;
import org.springframework.beans.factory.annotation.Autowired;
public class People {
    @Autowired
    private Cat cat;
    @Autowired
    private Dog dog;
    public Cat getCat() {
        return cat;
    }
    public Dog getDog() {
        return dog;
    }
    @Override
    public String toString() {
        return "People{" +
                "cat=" + cat +
                ", dog=" + dog +
                '}';
    }
}

Cat實體類

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

Dog實體類

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

使用@Autowired注解支持自動注入后,可以省略實體類的setter方法

3、測試結果

在這里插入圖片描述

使用Java類庫中的@Resource注解可以實現(xiàn)相同的效果,@Autowired和@Resource注解的區(qū)別是

  • @Autowired注解默認按byType方式實現(xiàn),@Resource注解默認按byName方式實現(xiàn)
  • @Autowired注解在IOC容器中配置了多個相同類型的bean時,需要配合@Qualifier找到唯一bean
@Autowired
@Qualifier("cat")
private Cat cat;

@Resource注解可以配置name和type屬性進行bean的注入

@Resource(name = "dog", type = Dog.class)
private Dog dog;


@Resource屬性單獨使用name屬性后,將不會按照byType方式查找bean,@Autowired注解可以使用required屬性來決定注入的屬性是否允許為空

@Autowired(required = false)
 @Qualifier("cat")
 private Cat cat;

@Autowired注解的使用和注入規(guī)則

作為一個Spring開發(fā)者對@Autowired注解必定是非常了解了, 顧名思義自動裝配,應該是Spring會自動將我們標記為@Autowired的元素裝配好,與其猜測不如看看它的定義:

@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired { 
  boolean required() default true; 
}

很明顯這個注解可以用到構造器,變量域,方法,注解類型和方法參數(shù)上。文檔上這樣描述:將一個構造器,變量域,setter方法,config方法標記為被Spring DI 工具自動裝配。換句話說,在Spring創(chuàng)建bean的過程中,會為這個bean中標有@Autowired注解的構造器,變量域,方法和方法參數(shù)中自動注入我們需要的已經在Spring IOC容器里面的bean,,而無需我們手動完成,并且注入的bean都是單實例,也就是在兩個bean中都依賴第三個bean,那么這兩個bean中注入的第三個bean會是同一個bean(JVM中指向的地址相同)。

在@Autowired注解里面有一個required屬性,該屬性默認為true,當為true時,表示去Spring IOC中查找相應的bean,如果找不到,則會報錯,如果為false時,表示去Spring IOC中查找相應的bean,如果找不到,則直接忽略,不再進行注入。

@Autowired注解的注入規(guī)則:默認按照類型進行注入,如果IOC容器中存在兩個及以上的相同類型的bean時,根據(jù)bean的名稱進行注入,如果沒有指定名稱的bean,則會報錯。

可以使用@Qualifier("wheel")來使用指定id的bean,也可以在注入bean時,添加@Primary注解,優(yōu)先添加一個bean,其規(guī)則如下:

如果指定添加了@Qualifier("wheel")則按照指定的bean id進行添加(優(yōu)先級最高),找不到則直接報錯。如果沒有添加@Qualifier而添加了@Primary注解,則首先添加標注了@Primary注解的bean。當即存在@Qualifier注解也存在@Primary注解注解,則按照@Qualifier指定的bean id注入,找不到直接報錯。

很多人java開發(fā)者都知道@Autowired注解,但是真正用的好的也不多(反正系統(tǒng)的學習Spring之前我是不知道的),那下面讓我們來看一下@Autowired的用法:

1.使用在變量域上面

這個相信大家都已經清楚了,Spring會幫我們注入我們想要的bean,看下面的例子:

package it.cast.circularDependency; 
@Component
public class Wheel { 
}
 
@Component
public class Car { 
    @Autowired
    private Wheel wheel2;
 
    public Wheel getWheel() {
        return wheel2;
    }
 
    public void setWheel(Wheel wheel2) {
        this.wheel2 = wheel2;
    }
}
 
@ComponentScan({"it.cast.circularDependency"})
public class AutowiredConfig { 
}

下面進行測試,打印的結果顯示可以拿到Wheel類,說明@Autowired注解在IOC容器中只有一個類型的bean時,按照類型進行注入。

@Test
    public void AutowiredConfigTest(){
        AnnotationConfigApplicationContext context =
                new AnnotationConfigApplicationContext(AutowiredConfig.class); 
        Car bean = context.getBean(Car.class);
        System.out.println(bean.getWheel());
    }
 
//打印結果:
//   it.cast.circularDependency.Wheel@3eb25e1a

下面看一下當IOC容器中有兩個Wheel類型的bean時的情況,改造Wheel類,增加一個屬性標識用于記錄向Car類中注入的哪個Wheel的bean,在AutowiredConfig配置類中添加一個bean,bean的名稱默認為方法名,也就是wheel1。

@Component
public class Wheel {
    private int num = 2;   //通過包掃描的方式注入的bean的num值為2 
    public int getNum() {
        return num;
    } 
    public void setNum(int num) {
        this.num = num;
    }
}
 
@Component
public class Car { 
    @Autowired
    private Wheel wheel3;//將變量名改成wheel3,IOC容器中Wheel類型的bean的名稱只有wheel和wheel1 
    public Wheel getWheel() {
        return wheel3;
    } 
    public void setWheel(Wheel wheel3) {
        this.wheel3 = wheel3;
    }
} 
 
@Configuration
@ComponentScan({"it.cast.circularDependency"})
public class AutowiredConfig {
 
    @Bean
    public Wheel wheel1(){ 
        Wheel wheel = new Wheel();//通過配置類注入bean的方式num值為0
        wheel.setNum(0);
        return wheel;
    }
}

這時在Spring IOC中有兩個Wheel類型的bean了,Car在注入Wheel類型的bean時,會根據(jù)變量名wheel3去找,也就是說會去找類型為Wheel,名稱為wheel3的bean,顯然是找不到的,也就會報錯。

Exception encountered during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'car':
Unsatisfied dependency expressed through field 'wheel3';
nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException:
No qualifying bean of type 'it.cast.circularDependency.Wheel' available:
expected single matching bean but found 2: wheel,wheel1

org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'car': Unsatisfied dependency expressed through field 'wheel3';
nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException:
No qualifying bean of type 'it.cast.circularDependency.Wheel' available:
expected single matching bean but found 2: wheel,wheel1

上面為報錯的日志打印,大致意思說的在創(chuàng)建名稱為car的bean時,不能為變量域wheel3完成屬性注入,因為找到了兩個bean,分別是wheel和wheel1。

如果我們把Car中的wheel3換成wheel就可以完成注入了,而且注入的bean是通過包掃描注入IOC的bean:

@Component
public class Wheel {
    private int num = 2;   //通過包掃描的方式注入的bean的num值為2 
    public int getNum() {
        return num;
    } 
    public void setNum(int num) {
        this.num = num;
    }
}
 
@Component
public class Car { 
    @Autowired
    private Wheel wheel;//將變量名改成wheel1,IOC容器中Wheel類型的bean的名稱只有wheel和wheel1 
    public Wheel getWheel() {
        return wheel;
    } 
    public void setWheel(Wheel wheel3) {
        this.wheel = wheel;
    }
} 
 
@Configuration
@ComponentScan({"it.cast.circularDependency"})
public class AutowiredConfig { 
    @Bean
    public Wheel wheel1(){ 
        Wheel wheel = new Wheel();//通過配置類注入bean的方式num值為0
        wheel.setNum(0);
        return wheel;
    }
}

在測試類中打印num值看看注入的是哪個bean:

@Test
    public void AutowiredConfigTest(){
        AnnotationConfigApplicationContext context =
                new AnnotationConfigApplicationContext(AutowiredConfig.class);
 
        Car bean = context.getBean(Car.class);
        System.out.println(bean.getWheel().getNum());
    } 
//打印結果:
//    2

那么就驗證了上面所說的注入規(guī)則:默認按照類型進行注入,如果IOC容器中存在兩個及以上的相同類型的bean時,根據(jù)bean的名稱進行注入,如果沒有指定名稱的bean,則會報錯。

@Autowired注解使用在變量域中還可以解決循環(huán)依賴的問題,循環(huán)依賴問題就是A對象中注入了B對象,B對象中注入了A對象,循環(huán)依賴在面試Spring這一塊的知識應該經常會被問題,關于循環(huán)依賴的問題,在后面的博客中會更新。

2.@Autowired注解使用在構造器上面

@Autowired使用在構造器上面有幾條需要特別注意的點:

1.@Autowired標注在構造器上面不能解決循環(huán)依賴構造的問題

2.@Autowired可以標注在同一個類的多個構造器上面,但是required屬性必須都為false,當required有一個為true時,不允許其他構造器標有@Autowired注解,即使required屬性為false也不行。

@Component
public class A {
    private B b;
    private C c;
 
    @Autowired
    public A(B b, C c) {
        System.out.println("b=" + b + ", c=" + c);
        this.b = b;
        this.c = c;
    }
}
 
@Component
public class B { 
} 
@Component
public class C {
}
 
//打印結果:
//  b=it.cast.circularDependency.B@68e965f5, c=it.cast.circularDependency.C@6f27a732

@Autowired標注在構造器上面,在B創(chuàng)建的過程中,會去Spring IOC中拿到需要的注入的bean,完成B的創(chuàng)建,其實在只有一個構造器的情況中,@Autowired可以不加,因為Spring內部有自動推斷構造器的能力,這個如果想了解自動推斷構造器的同學可以自行百度(實在是太難了,一臉蒙蔽)。

下面看一個構造器循壞依賴的案例:

@Component
public class C {
    private B b; 
    public C(B b) {
        this.b = b;
    }
}
 
@Component
public class B {
    private C c; 
    public B(C c) {
        this.c = c;
    }
}

Spring目前不能解決構造器的循環(huán)依賴,所以在項目中使用的時候要格外注意一下,錯誤日志:

org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'a' defined in file
[E:\IdeaProjects\javaBasis\spring\target\classes\it\cast\circularDependency\A.class]:
Unsatisfied dependency expressed through constructor parameter 0;
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'b' defined in file
[E:\IdeaProjects\javaBasis\spring\target\classes\it\cast\circularDependency\B.class]:
Unsatisfied dependency expressed through constructor parameter 0;
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'c' defined in file
[E:\IdeaProjects\javaBasis\spring\target\classes\it\cast\circularDependency\C.class]:
Unsatisfied dependency expressed through constructor parameter 0;
nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException:
Error creating bean with name 'b':
Requested bean is currently in creation: Is there an unresolvable circular reference?

下面看一下關于多個@Autowired標注的構造器的案例:

@Component
public class A {
    private B b;
    private C c; 
    @Autowired(required = false)
    public A(B b) {
        this.b = b;
    }
 
    @Autowired
    public A(B b, C c) {
        System.out.println("b=" + b + ", c=" + c);
        this.b = b;
        this.c = c;
    }
} 
@Component
public class B { 
} 
@Component
public class C { 
}

上面已經說到,如果@Autowired注解的屬性required為true時,不允許再出現(xiàn)其他構造器上面標有@Autowired注解(@Autowired注解的required默認為true,所以上面的會報錯),錯誤日志為:

org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'a': Invalid autowire-marked constructors:
[public it.cast.circularDependency.A(it.cast.circularDependency.B)].
Found constructor with 'required' Autowired annotation:
public it.cast.circularDependency.A(it.cast.circularDependency.B,it.cast.circularDependency.C)

使用下面的寫法就不會出現(xiàn)錯誤了,Spring支持多個構造器有@Autowired注解,但是required屬性必須都是false

@Component
public class A {
    private B b;
    private C c;
 
    @Autowired(required = false) 
    public A(B b) {
        this.b = b;
    }
 
    @Autowired(required = false)
    public A(B b, C c) {
        System.out.println("b=" + b + ", c=" + c);
        this.b = b;
        this.c = c;
    }
}
 
@Component
public class B { 
} 
@Component
public class C { 
}

關于@Autowired標注在方法上就不多介紹,會首先拿到方法的參數(shù)列表,然后根據(jù)上面所說的注入規(guī)則去Spring IOC中找相應的bean。

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

  • 通過實例解析java8中的parallelStream

    通過實例解析java8中的parallelStream

    這篇文章主要介紹了通過實例解析java8中的parallelStream,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2019-11-11
  • Lombok插件有望被Intellij IDEA收編以改善兼容性問題(推薦)

    Lombok插件有望被Intellij IDEA收編以改善兼容性問題(推薦)

    這篇文章主要介紹了Lombok插件有望被Intellij IDEA收編以改善兼容性問題,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-08-08
  • SpringBoot @ExceptionHandler與@ControllerAdvice異常處理詳解

    SpringBoot @ExceptionHandler與@ControllerAdvice異常處理詳解

    在Spring Boot應用的開發(fā)中,不管是對底層數(shù)據(jù)庫操作,對業(yè)務層操作,還是對控制層操作,都會不可避免的遇到各種可預知的,不可預知的異常需要處理,如果每個處理過程都單獨處理異常,那么系統(tǒng)的代碼耦合度會很高,工作量大且不好統(tǒng)一,以后維護的工作量也很大
    2022-10-10
  • mybatis返回key value map集合方式

    mybatis返回key value map集合方式

    這篇文章主要介紹了mybatis返回key value map集合方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-01-01
  • IDEA創(chuàng)建Servlet并配置web.xml的實現(xiàn)

    IDEA創(chuàng)建Servlet并配置web.xml的實現(xiàn)

    這篇文章主要介紹了IDEA創(chuàng)建Servlet并配置web.xml的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-10-10
  • ShardingSphere jdbc實現(xiàn)分庫分表核心概念詳解

    ShardingSphere jdbc實現(xiàn)分庫分表核心概念詳解

    這篇文章主要為大家介紹了ShardingSphere jdbc實現(xiàn)分庫分表核心概念詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-12-12
  • Springboot配置返回日期格式化五種方法詳解

    Springboot配置返回日期格式化五種方法詳解

    本文主要介紹了Springboot配置返回日期格式化五種方法詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2022-07-07
  • SpringBoot如何實現(xiàn)一個實時更新的進度條的示例代碼

    SpringBoot如何實現(xiàn)一個實時更新的進度條的示例代碼

    本文詳細的介紹了SpringBoot如何實現(xiàn)一個實時更新的進度條,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-05-05
  • 使用RocketMQTemplate發(fā)送帶tags的消息

    使用RocketMQTemplate發(fā)送帶tags的消息

    這篇文章主要介紹了使用RocketMQTemplate發(fā)送帶tags的消息,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • Java本地緩存的實現(xiàn)代碼

    Java本地緩存的實現(xiàn)代碼

    本篇文章主要介紹了Java本地緩存的實現(xiàn)代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-05-05

最新評論

营口市| 鄢陵县| 印江| 巫溪县| 饶阳县| 隆安县| 山阳县| 龙游县| 巴中市| 湾仔区| 正宁县| 宜昌市| 阳高县| 延寿县| 惠安县| 马尔康县| 巴林左旗| 宝坻区| 久治县| 恭城| 南通市| 宜城市| 平顺县| 琼结县| 金昌市| 仙居县| 子洲县| 焉耆| 云安县| 天气| 灵武市| 扎赉特旗| 确山县| 隆林| 桃园市| 城固县| 虞城县| 沙雅县| 黄冈市| 菏泽市| 平凉市|