1. 程式人生 > >Spring Boot之省略注入

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方法呼叫的自動注入情況