自定义一个SpringBoot Starter

本文介绍了Spring Boot自定义starter的开发方法。首先阐述了自定义starter包含的模块,接着说明使用Spring Initializr创建项目及命名规则,然后依次讲解定义配置信息映射类、Service、配置类自动装配Service等步骤,最后通过maven将其安装到本地仓库并进行测试。

简介

官方文档中关于自定义starter的描述

4.29.5. Creating Your Own Starter
Concretely, a custom starter can contain the following:
• The autoconfigure module that contains the auto-configuration code for “acme”.
• The starter module that provides a dependency to the autoconfigure module as well as “acme” and any additional dependencies that are typically useful. In a nutshell, adding the starter should provide everything needed to start using that library.

  • autoconfigure module 代码写在此moudle中
  • starter module只是一个空的项目,它的唯一目的是提供必要的依赖

如果配置简单,没有可选项,可以把所有东西都写在一个Moudle中

使用Spring Initializr创建一个项目

SpringBoot提供的starter以spring-boot-starter-xxx的方式命名的。官方建议自定义的starter使用xxx-spring-boot-starter命名规则。以区分SpringBoot生态提供的starter。

删掉一些不需要的东西,项目结构和pom如下:
在这里插入图片描述

<?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.xgsama</groupId>
    <artifactId>xg-spring-boot-starter</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

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

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>
</project>

定义一个配置信息映射类

package com.xgsama.starter.autoconfigure;

import org.springframework.boot.context.properties.ConfigurationProperties;
// 该注解有一个prefix属性,通过指定的前缀,绑定配置文件中的配置
@ConfigurationProperties("xg.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;
    }
}

定义一个Service

package com.xgsama.starter.service;

import com.xgsama.starter.autoconfigure.HelloProperties;

import javax.annotation.Resource;

/**
 * HelloService
 *
 * @author xgSama
 * @date 2021/1/10 22:59
 */
public class HelloService {
    @Resource
    HelloProperties properties;

    public String sayHello(String name) {

        return properties.getPrefix() + ":" + name + "!" + properties.getSuffix();
    }
}

定义一个配置类自动装配Service

@EnableConfigurationProperties使 @ConfigurationProperties 注解的类生效
@ConditionalOnMissingBean指定在某个Bean不存在时配置才生效

package com.xgsama.starter.autoconfigure;

import com.xgsama.starter.service.HelloService;
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;

/**
 * HelloServiceAutoConfiguration
 *
 * @author xgSama
 * @date 2021/1/10 22:59
 */
@Configuration
@EnableConfigurationProperties(HelloProperties.class)
public class HelloServiceAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean(HelloService.class)
    public HelloService helloService() {
        return new HelloService();
    }
}

在spring.factories中指定自动装配的类

在classpath下创建META-INF,新建spring.factories文件
在这里插入图片描述
添加以下内容,指定上步骤中定义的配置类为自动装配的配置。

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.xgsama.starter.autoconfigure.HelloServiceAutoConfiguration

安装测试

执行maven clean install将自定义的starter安装到本地maven仓库,新建一个Spring Boot测试这个starter
引入依赖

<dependency>
	<groupId>com.xgsama</groupId>
	<artifactId>xg-spring-boot-starter</artifactId>
	<version>1.0-SNAPSHOT</version>
</dependency>

添加配置

server:
  port: 8888
xg:
  hello:
    prefix: hello
    suffix: nice to meet you

编写测试Controller

/**
 * AlphaController
 *
 * @author xgSama
 * @date 2020/12/26 10:44
 */
@RestController
public class AlphaController {

    @Resource
    HelloService helloService;

    @GetMapping("/hello")
    public String hello() {
        String sayHello = helloService.sayHello("玄戈");
        return sayHello;
    }
}

启动项目测试
在这里插入图片描述

<think>嗯,用户想了解如何创建和配置自定义Spring Boot Starter。我之前看过一些相关的资料,记得Spring BootStarter主要是为了简化依赖管理和自动配置。用户可能需要知道整个流程,包括创建项目、添加依赖、编写自动配置类等步骤。 首先,得确定用户可能的需求。他们可能是想将一些常用的功能封装成Starter,方便在不同项目中复用。比如数据库连接、工具类等。所以教程需要详细步骤,从项目结构开始,到自动配置的实现,再到测试和使用。 然后,根据引用资料里的内容,引用[2]提到了自定义Starter的示例,引用[3]强调组件化和模块化的帮助,引用[4]则给出了一个例子,特别是Autoconfigure类。需要整合这些信息,确保步骤正确。 接下来,我应该分步骤讲解:创建模块、添加依赖、配置属性类、自动配置类、注册配置、创建spring.factories文件,最后是打包和使用。可能还需要提到条件注解,如@ConditionalOnClass,来确保自动配置的条件性。 用户可能对每个步骤的具体代码实现有疑问,所以需要给出代码示例,比如HelloProperties配置类,HelloService业务类,以及HelloAutoConfiguration自动配置类。同时,要提醒他们Maven的依赖管理和spring.factories的位置,这在Spring Boot自动配置中很关键。 另外,测试部分也很重要,用户可能需要知道如何引入自定义Starter并进行测试,所以需要添加测试步骤,比如创建测试项目,添加依赖,使用@Autowired注入服务类,并编写测试用例。 最后,常见问题部分可以帮助用户避免一些坑,比如配置不生效,可能是spring.factories未正确配置,或者缺少必要的注解。同时,版本管理的问题,确保StarterSpring Boot版本兼容。 总结一下,需要结构清晰,步骤明确,代码示例具体,并涵盖可能遇到的问题。这样用户才能顺利创建和配置自己的Spring Boot Starter。</think>### 自定义 Spring Boot Starter 创建与实现教程 #### 1. **核心概念** Spring Boot Starter一个模块化依赖包,包含自动配置、依赖管理和组件定义。其核心目标是**简化模块集成**,通过`@Conditional`注解实现环境感知的自动配置[^1]。 #### 2. **实现步骤** ##### 2.1 创建 Maven 模块 新建两个模块: - `xxx-spring-boot-autoconfigure`(自动配置核心) - `xxx-spring-boot-starter`(依赖聚合包) ##### 2.2 添加关键依赖 ```xml <!-- autoconfigure模块的pom.xml --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-autoconfigure</artifactId> </dependency> ``` ##### 2.3 编写配置属性类 ```java @ConfigurationProperties(prefix = "hello") public class HelloProperties { private String defaultName = "Guest"; // getters/setters } ``` ##### 2.4 创建业务服务类 ```java public class HelloService { private final String name; public HelloService(String name) { this.name = name; } public String sayHello() { return "Hello, " + name; } } ``` ##### 2.5 实现自动配置类 ```java @Configuration @ConditionalOnClass(HelloService.class) @EnableConfigurationProperties(HelloProperties.class) public class HelloAutoConfiguration { @Bean @ConditionalOnMissingBean public HelloService helloService(HelloProperties properties) { return new HelloService(properties.getDefaultName()); } } ``` ##### 2.6 注册自动配置 在`resources/META-INF`下创建`spring.factories`: ```properties org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.example.HelloAutoConfiguration ``` #### 3. **测试验证** ```java @SpringBootTest public class HelloServiceTest { @Autowired private HelloService helloService; @Test public void testSayHello() { assertThat(helloService.sayHello()).isEqualTo("Hello, Guest"); } } ``` #### 4. **高级配置技巧** - **条件化加载**:使用`@ConditionalOnProperty`控制配置生效条件 - **配置元数据**:添加`spring-configuration-metadata.json`支持IDE提示 - **模块分离**:将注解处理器与实现分离提升扩展性[^3] #### 5. **常见问题排查** - **配置未生效**:检查`spring.factories`路径和自动配置类包扫描范围 - **属性注入失败**:确认`@EnableConfigurationProperties`位置 - **版本冲突**:通过`mvn dependency:tree`分析依赖关系
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值