学无先后,达者为师

网站首页 编程语言 正文

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

栏目分类
最近更新