You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建Spring Boot Starter自动初始化默认配置属性

创建自定义Spring Boot Starter实现默认配置自动生效

1. 搭建Starter基础项目

用Spring Initializr生成一个Maven/Gradle项目,GroupId填你的组织标识(比如com.yourcompany),ArtifactId命名为custom-server-starter——不用添加任何依赖,咱们只需要放配置文件就能满足需求。

2. 添加默认配置文件

在项目的src/main/resources目录下新建application.properties,直接写入需要的默认配置:

server.port=8443
server.ssl.enabled=true

注:如果后续需要自定义业务专属属性(而非Spring自带的server类配置),可以配合@ConfigurationProperties写配置类,但本次需求仅覆盖Spring原生配置,直接写这个文件就足够。

3. 打包发布Starter

如果是Maven项目,确保pom.xml里的打包方式为jar,并配置正确的坐标信息:

<groupId>com.yourcompany</groupId>
<artifactId>custom-server-starter</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.7.15</version> <!-- 选择与业务项目兼容的Spring Boot版本 -->
    <relativePath/>
</parent>

执行mvn clean install将Starter安装到本地Maven仓库,或者发布到公司私有仓库,方便其他项目引用。

4. 业务项目中快速使用

在需要这套默认配置的Spring Boot项目的pom.xml中添加依赖:

<dependency>
    <groupId>com.yourcompany</groupId>
    <artifactId>custom-server-starter</artifactId>
    <version>1.0.0</version>
</dependency>

启动项目后,会自动使用8443端口并开启SSL,无需在业务项目的application.properties中手动配置。如果某个项目需要自定义配置,直接在自身的application.properties中写入对应属性即可,会自动覆盖Starter中的默认值。

额外扩展说明

如果后续需要添加自定义业务配置项,可以按以下方式操作:

  1. 编写配置类,用@ConfigurationProperties指定属性前缀:
    @ConfigurationProperties(prefix = "custom")
    public class CustomProperties {
        // 设置默认值
        private String appName = "default-business-app";
    
        // 必须添加getter和setter方法
        public String getAppName() {
            return appName;
        }
    
        public void setAppName(String appName) {
            this.appName = appName;
        }
    }
    
  2. 在src/main/resources/META-INF/spring目录下新建org.springframework.boot.autoconfigure.AutoConfiguration.imports文件,写入配置类的全路径:
    com.yourcompany.customserverstarter.CustomProperties
    
  3. 在Starter的application.properties中给自定义属性设置默认值,业务项目即可直接使用,也能随时覆盖。

内容的提问来源于stack exchange,提问作者Eduardo Ito

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 08:25:21