Spring Boot之省略注入

Spring提供的標註,其基於容器自動尋找和加載特定的對象。

其尋找和匹配的範圍包括: @Component, @Bean, @Service, @Repository, @Controller等聲明的對象。使用方式@Autowired可以用在屬性、方法和構造函數上。

查看其定義如下:@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface Autowired {    /** * Declares whether the annotated dependency is required. *Defaults to {@code true}. */ boolean required() default true; }

基於其標註定義,可以知道其使用的Target如上所示,幾乎適用於各個場景。 某些場景下的省略 以下是基於構造方法的加載: package com.example.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class DatabaseAccountService implements AccountService { private final RiskAssessor riskAssessor; @Autowired public DatabaseAccountService(RiskAssessor riskAssessor) { this.riskAssessor = riskAssessor; } // ... }

以下是等價的自動加載方式: @Service public class DatabaseAccountService implements AccountService { private final RiskAssessor riskAssessor; public DatabaseAccountService(RiskAssessor riskAssessor) { this.riskAssessor = riskAssessor; } // ... }

根據其官方說明 If a bean has one constructor, you can omit the @Autowired 於是這裏就可以省略@Autowired。 還有其他類似省略的注入情況嗎? 有,當然有,Java初高級一起學習分享,喜歡的話可以我的學習羣64弍46衣3凌9,或加資料羣69似64陸0吧3基於@Bean註解方法之時,如果方法中有參數的話,則自動進行注入加載。 示例如下: @Configuration class SomeConfiguration { @Bean public SomeComponent someComponent(Depend1 depend1, @Autowired(required = false) Depend2 depend2) { SomeComponent someComponent = new SomeComponent(); someComponent.setDepend1(depend1); if (depend2 != null) { someComponent.setDepend2(depend2); } return someComponent; } }

在上述示例中,Depend1是自動注入的, Depend2是可選的注入,爲了使用required=false的設置,則這裏使用了@Autowired,默認情況下是無需使用的。 總結 在實際使用和開發中,需要注意構造方法以及@Bean方法調用的自動注入情況

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章