日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

SpringBoot 實現自定義的 starter

作者:tytler 更新時間: 2022-08-28 編程語言
starter 是什么 ?
  • 日常開發中,開發者可以封裝屬于自己框架的 starter,可以實現自動配置,可以設定有哪些配置屬性,通過屬性去控制 starter 的使用,就像使用集成 spring-boot 的 starter
  • starter 是可插拔插件,和 jar 包的區別是 starter 能實現自動配置,能夠大幅提升開發效率

常用的 starter

請添加圖片描述

如何 創建自定義 和 使用 starter ?
  • 創建 starter 步驟
    • 新建 springboot 項目
    • 引入 spring-boot-autoconfigure 依賴
    • 編寫屬性源及自動配置類
      • 通過 @Configuration 注解標注配置類,通過 @Bean 標注方法返回的對象
      • 創建一個配置文件,并且通過 @EnableConfigurationProperties() 使配置文件生效
      • 通過 @ConditionalOnProperty() 注解指定配置文件的屬性,某個屬性為某個值就自動將 bean 對象注入到 spring 容器中
    • 在 spring.factories 中添加自動配置實現類
    • maven 打包,讓其他工程可依賴

  • 使用 starter 步驟
    • pom.xml 中引入 starter
    • 屬性文件中配置屬性
    • 類中引用服務,調用服務能力

starter 的實現原理
  • 通過 @EnableAutoConfiguration 注解注入 bean 的流程
    • 啟動類 @SpringBootApplication
    • 引入 AutoConfigurationImportSelector
    • ImportSelector 的 selectImport 方法返回 String[] 數組
    • ConfigurationClassParser 中處理
    • 獲取 spring.factories 中 EnableAutoConfiguration 的實現

  • @ConditionalOnProperties 注解注入 bean 原理
    • @ConditionalOnProperty() 方式注入 bean 對象
    • OnPropertyCondition,繼承 SpringBootCondition 實現 Condition 接口
    • ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) 方法
    • 遍歷注解屬性判斷 environment 中是否含有并且值一直
    • 返回對比結果,Condition 的 matches() 方法返回 true,就注入到 spring 容器中

原文鏈接:https://blog.csdn.net/qq_41956014/article/details/126560650

欄目分類
最近更新