首頁  >  文章  >  Java  >  怎麼在springboot自訂Starter

怎麼在springboot自訂Starter

PHPz
PHPz轉載
2023-05-28 15:25:461615瀏覽

自訂Starter命名規則

注意artifactId的命名規則,Spring官方Starter通常命名為spring-boot-starter-{name}如spring-boot-starter -web, Spring官方建議非官方Starter命名應遵循{name}-spring-boot-starter的格式, 如mybatis-spring-boot-starter。這裡建立的專案的artifactId為helloworld-spring-boot-starter

#開發Starter步驟

  • #建立Starter項目

  • 定義Starter需要的設定(Properties)類別

  • #編寫自動配置類別

  • ##編寫spring.factories檔案載入自動配置類別
  • 編寫設定提示檔spring-configuration-metadata.json(不是必須的)
具體流程


建立配置類別


@ConfigurationProperties 來定義配置的前綴

@EnableConfigurationProperties(InfluxdbProperties.class)
@ConfigurationProperties(prefix = "spring.influxdb")
public class InfluxdbProperties {
 private String username;
 public String getDatabase() {
   return database;
 }
 public void setDatabase(String database) {
   this.database = database;
 }
}

編寫自動配置類別

    @EnableConfigurationProperties配置依賴的屬性類別
  • @ConditionalOnProperty 設定Configuration的載入規則
    • #value 指的是Properties的哪個欄位
    • havingValue指的是設定value是什麼值的時候載入Configuration
    • matchIfMissing 指的是當value配置的欄位沒有配置時的預設值
    @Bean 配置自動注入的bean
  • springboot特有的常見的條件依賴註解有:
    • @ConditionalOnBean,只有當目前上下文中存在某個bean時,才會實例化這個Bean。
    • @ConditionalOnClass,某個class位於類別路徑上,才會實例化這個Bean。
    • @ConditionalOnExpression,當表達式為true的時候,才會實例化這個Bean。
    • @ConditionalOnMissingBean,只有在目前上下文中不存在某個bean時,才會實例化這個Bean。
    • @ConditionalOnMissingClass,某個class在類別路徑上不存在的時候,才會實例化這個Bean。
    • @ConditionalOnNotWebApplication,不是web應用程式時才會實例化這個Bean。
    • @AutoConfigureAfter,在某個bean完成自動設定後實例化這個bean。
    • @AutoConfigureBefore,在某個bean完成自動設定前實例化這個bean。
@Configuration
@Order(1)
@EnableConfigurationProperties(InfluxdbProperties.class)
@ConditionalOnClass(InfluxdbProperties.class)
@ConditionalOnProperty(prefix = "spring.influxdb", value = "use-influxdb", havingValue="true" ,matchIfMissing = false)
public class InfluxdbAutoConfiguration {
private String scanEntitySuffix = "Entity.class";

@Bean
@ConditionalOnMissingBean(AiInfluxdbTemplate.class)
@Order(Ordered.HIGHEST_PRECEDENCE)
public AiInfluxdbTemplate AiInfluxdbTemplate(InfluxdbProperties influxdbProperties){
  return new AiInfluxdbTemplate(influxdbProperties);
}
}
編寫spring.factories檔案


#Spring Boot會預設掃描跟啟動類別平級的包,如果我們的Starter跟啟動類不在同一個主套件下,需要透過設定spring.factories檔案來生效

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.ai.base.boot.influxdb.InfluxdbAutoConfiguration

以上是怎麼在springboot自訂Starter的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除