【SpringBoot】37 核心功能 - 高级特性- Spring Boot 中的 自定义 Starter 完整教程

前言

在 Spring Boot 中,自定义 Starter 是一种非常强大的方式,可以将常用的功能模块封装成可复用的组件。本文将详细介绍如何创建一个自定义 Starter,并提供完整的使用流程和代码示例。


一、自定义 Starter 原理

Spring Boot 的[自动配置]机制依赖于 META-INF/spring.factories 文件中的 EnableAutoConfiguration [配置项]。当项目启动时,Spring Boot 会扫描所有 META-INF/spring.factories 文件,加载其中指定的自动配置类。

启动流程图解:

bash 复制代码
starter → autoconfigure → spring-boot-starter
         ↑
         └─ META-INF/spring.factories

AI写代码
123
  • starter:Maven/Gradle 依赖包(启动器)
  • autoconfigure:包含自动配置逻辑的包
  • spring.factories:配置自动配置类的入口文件

二、项目结构设计

我们以一个简单的"Hello World"功能为例,创建一个名为 atguigu-hello-spring-boot-starter 的自定义 Starter。

1. 模块划分

css 复制代码
├── atguigu-hello-spring-boot-starter (Starter)
│   ├── pom.xml
│   └── src/main/java/com/atguigu/hello/HelloService.java
│
├── atguigu-hello-spring-boot-starter-autoconfigure (Autoconfigure)
│   ├── pom.xml
│   ├── src/main/java/com/atguigu/hello/config/HelloAutoConfiguration.java
│   ├── src/main/java/com/atguigu/hello/config/HelloProperties.java
│   └── src/main/resources/META-INF/spring.factories

AI写代码
123456789

三、代码实现

1. 创建 Autoconfigure 模块

pom.xml
xml 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.atguigu</groupId>
    <artifactId>atguigu-hello-spring-boot-starter-autoconfigure</artifactId>
    <version>1.0.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.1.5</version>
        <relativePath/>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
    </dependencies>
</project>

AI写代码xml
12345678910111213141516171819202122232425
HelloProperties.java(配置属性类)
typescript 复制代码
package com.atguigu.hello.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "hello")
public class HelloProperties {

    private String message = "Hello, World!";

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

AI写代码java
运行
12345678910111213141516171819
HelloAutoConfiguration.java(自动配置类)
kotlin 复制代码
package com.atguigu.hello.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties(HelloProperties.class)
public class HelloAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public HelloService helloService(HelloProperties properties) {
        return new HelloService(properties.getMessage());
    }
}

AI写代码java
运行
1234567891011121314151617
HelloService.java(业务逻辑类)
arduino 复制代码
package com.atguigu.hello;

public class HelloService {

    private final String message;

    public HelloService(String message) {
        this.message = message;
    }

    public String sayHello() {
        return message;
    }

    public void printHello() {
        System.out.println(sayHello());
    }
}

AI写代码java
运行
123456789101112131415161718
META-INF/spring.factories
ini 复制代码
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.atguigu.hello.config.HelloAutoConfiguration

AI写代码properties
12

注意:spring.factories 文件必须放在 src/main/resources/META-INF/ 目录下。


2. 创建 Starter 模块

pom.xml
xml 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.atguigu</groupId>
    <artifactId>atguigu-hello-spring-boot-starter</artifactId>
    <version>1.0.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.1.5</version>
        <relativePath/>
    </parent>

    <dependencies>
        <!-- 引入 autoconfigure 包 -->
        <dependency>
            <groupId>com.atguigu</groupId>
            <artifactId>atguigu-hello-spring-boot-starter-autoconfigure</artifactId>
            <version>1.0.0</version>
        </dependency>
    </dependencies>
</project>

AI写代码xml
123456789101112131415161718192021222324252627

说明 :这个 starter 只是一个"门面",真正实现自动配置的是 autoconfigure 模块。


四、使用自定义 Starter

1. 在目标项目中引入 Starter

pom.xml
xml 复制代码
<dependency>
    <groupId>com.atguigu</groupId>
    <artifactId>atguigu-hello-spring-boot-starter</artifactId>
    <version>1.0.0</version>
</dependency>

AI写代码xml
12345

2. 配置文件 application.yml

makefile 复制代码
hello:
  message: "Hello, Spring Boot!"

AI写代码yaml
12

3. 编写测试代码

typescript 复制代码
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Autowired
    private HelloService helloService;

    @PostConstruct
    public void init() {
        helloService.printHello(); // 输出: Hello, Spring Boot!
    }
}

AI写代码java
运行
123456789101112131415

五、完整流程总结

步骤 描述
1 创建 autoconfigure 模块,包含自动配置逻辑
2 编写 @Configuration 类,使用 @EnableConfigurationProperties 绑定配置
3 META-INF/spring.factories 中注册自动配置类
4 创建 starter 模块,仅依赖 autoconfigure
5 在主项目中引入 starter,无需额外配置
6 通过 application.yml 设置参数,自动生效

六、关键注解说明

注解 作用
@Configuration 标记为配置类
@EnableConfigurationProperties 启用配置属性绑定
@ConditionalOnMissingBean 当容器中没有该 Bean 时才创建
@Component 将类注册为 Spring Bean
@ConfigurationProperties 绑定配置文件前缀属性

七、扩展建议

  • 支持多环境配置(如 dev, prod
  • 添加日志记录或监控功能
  • 使用 @ConditionalOnClass@ConditionalOnProperty 实现更复杂的条件判断
  • 提供接口供外部扩展

八、注意事项

  1. spring.factories 文件格式必须正确,不能有空格或换行错误。
  2. 确保 autoconfigure 模块的 spring-boot-autoconfigure 依赖已添加。
  3. 启动器模块不要直接写业务逻辑,只做依赖管理。
  4. 版本号保持一致,避免冲突。

九、运行效果

启动项目后,[控制台输出]:

复制代码
Hello, Spring Boot!

AI写代码
1

说明自定义 Starter 成功加载并执行了自动配置逻辑。


总结:通过这种方式,你可以轻松地将任何功能封装为可复用的 Spring Boot Starter,提升开发效率与代码复用性。

相关推荐
踏浪无痕2 小时前
Maven父子模块Deploy的那些坑
后端·maven
bcbnb2 小时前
iOS 应用上架全流程实战解析,从证书到审核的完整开发者指南
后端
master_hl2 小时前
基于 Kafka 与时间轮实现高性能延迟消息
后端
a***13142 小时前
python的sql解析库-sqlparse
android·前端·后端
s***55813 小时前
Skywalking介绍,Skywalking 9.4 安装,SpringBoot集成Skywalking
spring boot·后端·skywalking
IT_陈寒3 小时前
Redis深度优化:10个让你的QPS提升50%的关键配置解析
前端·人工智能·后端
武子康4 小时前
大数据-157 Apache Kylin 全面指南:MOLAP 架构、Hive/Kafka 实战与实时 OLAP 落地
大数据·后端·apache kylin
ssshooter4 小时前
传参优于外部变量
前端·后端·面试
qq_22589174664 小时前
基于Python+Django餐饮评论大数据分析与智能推荐系统 毕业论文
开发语言·后端·python·信息可视化·数据分析·django