Spring Boot自定义starter

starter 是 SpringBoot 中一种非常重要的机制,它可以繁杂的配置统一集成到 starter 中,我们只需要通过 maven 将 starter 依赖引入到项目中,SpringBoot 就能自动扫描并加载相应的默认配置。starter 的出现让开发人员从繁琐的框架配置中解放出来,将更多的精力专注于业务逻辑的开发,极大的提高了开发效率。

在一些特殊情况下,我们也可以将一些通用功能封装成自定义的 starter 进行使用,本节我们将为您详细介绍如何自定义 starter。
命名规范
SpringBoot 提供的 starter 以 spring-boot-starter-xxx 的形式命名。为了与 SpringBoot 生态提供的 starter 进行区分,官方建议第三方开发者或技术(例如 Druid、Mybatis 等等)厂商自定义的 starter 使用 xxx-spring-boot-starter 的形式命名,例如 mybatis-spring-boot-starter、druid-spring-boot-starter 等等。
模块规范
Spring Boot 官方建议我们在自定义 starter 时,创建两个 Module :autoConfigure Module 和 starter Module,其中 starter Module 依赖于 autoConfigure Module。当然,这只是 Spring Boot 官方的建议,并不是硬性规定,若不需要自动配置代码和依赖项目分离,我们也可以将它们组合到同一个 Module 里。
自定义 starter
自定义 starter 可以分为以下 7 步:
创建工程
添加 POM 依赖
定义 propertie 类
定义 Service 类
定义配置类
创建 spring.factories文件
构建 starter
创建工程

  1. 使用 IntelliJ IDEA 创建一个空项目(Empty Project),如下图。
    在这里插入图片描述

IDEA 创建一个空项目
图1:IDEA 创建空项目

  1. 在 Project Structure 界面,点击左上角的“+”按钮,选择“New Module”,新建一个名为 tangyu9880-hello-spring-boot-starter 的 Maven Module 和一个名为 tangyu9880-helllo-spring-boot-starter-autoconfiguration 的 Spring Boot Module,如下图。
    在这里插入图片描述

IDEA 创建两个 Module
图2:新建 Module
添加 POM 依赖
在 tangyu9880-hello-spring-boot-starter 的 pom.xml 中添加以下代码,将tangyu9880-helllo-spring-boot-starter-autoconfiguration 作为其依赖项。

tangyu9880 tangyu9880-helllo-spring-boot-starter-autoconfiguration 0.0.1-SNAPSHOT 定义 propertie 类 在 bianchengbang-helllo-spring-boot-starter-autoconfiguration 的 tangyu9880.properties 包中,创建一个实体类:HelloProperties,通过它来映射配置信息,其代码如下。 package tangyu9880.properties; import org.springframework.boot.context.properties.ConfigurationProperties; /** * 实体类,用来映射配置信息 */ @ConfigurationProperties("tangyu9880.hello") public class HelloProperties { private String prefix; private String suffix; public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getSuffix() { return suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } }

HelloProperties 类上使用了 @ConfigurationProperties(“net.biancheng.www.hello”),其含义是将该类中的属性与配置文件中的以 tangyu9880.hello 开头的配置进行绑定。
定义 Service 类
在 tangyu9880-helllo-spring-boot-starter-autoconfiguration 的 net.biacheng.www.service 中,创建一个 Service 类:HelloService,供其他项目使用,代码如下。
package tangyu9880.service;
import tangyu9880.properties.HelloProperties;
import org.springframework.beans.factory.annotation.Autowired;
/**

  • servcie 类,供外部调用
    */
    public class HelloService {
    @Autowired
    HelloProperties helloProperties;
    public String sayHello(String userN
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值