springboot中怎样自定义Starter

发布时间:2021-07-29 16:04:05 作者:Leah
来源:亿速云 阅读:126

这篇文章将为大家详细讲解有关springboot中怎样自定义Starter,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

自定义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就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. springboot中要如何自定义Starter
  2. 如何在springboot中自定义Starter

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

springboot starter

上一篇:java中如何自定义异常打印内容

下一篇:GridView中如何自定义分页的存储过程

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》