太强了!用 JSON 文件管理 Spring Boot 配置,简单又高效!

开发 前端
使用 @PropertySource​ 结合 PropertySourceFactory​ 是最直观的方式,而 ApplicationContextInitializer 适用于更高级的自定义需求。如果你想在 Spring Boot 项目中灵活管理配置,JSON 绝对是一个高效的选择!​

在 Spring Boot 3.4 中,JSON 配置文件管理提供了更灵活、高效的方式。开发者可以利用 @ConfigurationProperties 轻松绑定 JSON 配置,使应用程序启动时自动解析 JSON 数据,并将其加载到应用环境中。此外,还可以通过 spring.application.json 参数或 SPRING_APPLICATION_JSON 环境变量传递 JSON 数据,增强动态配置能力。本文将详细介绍如何使用 JSON 管理 Spring Boot 配置。

通过命令行加载 JSON 配置

在 Spring Boot 启动时,可以直接使用 spring.application.json 或 SPRING_APPLICATION_JSON 来动态提供 JSON 配置。

  • 使用环境变量:
SPRING_APPLICATION_JSON='{"server":{"port":8080}}' java -jar myapp.jar
  • 1.

这样,应用程序的 server.port 将被设置为 8080。

  • 通过 JVM 参数:
java -Dspring.application.json='{"server":{"port":8080}}' -jar myapp.jar
  • 1.
  • 作为启动参数:
java -jar myapp.jar --spring.application.json='{"server":{"port":8080}}'
  • 1.

尽管这种方式简单直接,但当 JSON 数据量较大时,手动维护会变得复杂,因此建议采用文件方式进行管理。

通过 @PropertySource 读取 JSON 配置

配置 JSON 文件

创建 JSON 配置文件 configprops.json,示例如下:

{
  "port": 8080,
  "host": "127.0.0.1"
}
  • 1.
  • 2.
  • 3.
  • 4.

创建 Java 配置类

package com.icoderoad.config;


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


@Component
@PropertySource(value = "classpath:configprops.json", factory = JsonPropertySourceFactory.class)
@ConfigurationProperties
public class JsonProperties {
    private Integer port;
    private String host;


    // Getters and Setters
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.

自定义 PropertySourceFactory

package com.icoderoad.config;


import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;


import java.io.IOException;
import java.util.Map;


public class JsonPropertySourceFactory implements PropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        Map<String, Object> readValue = new ObjectMapper().readValue(resource.getInputStream(), Map.class);
        return new MapPropertySource("json-property", readValue);
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.

处理 JSON 嵌套结构

当 JSON 结构中包含嵌套字段时,可以使用 Map 类型来映射子对象。

{
  "port":8080,
"host":"127.0.0.1",
"database":{
    "url":"jdbc:mysql://localhost:3306/test",
    "username":"root"
}
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

修改 Java 配置类:

package com.icoderoad.config;


import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import java.util.Map;


@Component
@PropertySource(value = "classpath:configprops.json", factory = JsonPropertySourceFactory.class)
@ConfigurationProperties
public class JsonProperties {
    private Integer port;
    private String host;
    private Map<String, Object> database;


    // Getters and Setters
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.

使用 ApplicationContextInitializer 读取 JSON 配置

如果需要更细粒度的控制,可以使用 ApplicationContextInitializer 进行手动加载。

package com.icoderoad.config;


import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.io.ClassPathResource;
import java.io.IOException;
import java.util.Map;


public class JsonPropertyContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
    @Override
    public void initialize(ConfigurableApplicationContext context) {
        try {
            Map<String, Object> jsonMap = new ObjectMapper().readValue(new ClassPathResource("configprops.json").getInputStream(), Map.class);
            context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("json-config", jsonMap));
        } catch (IOException e) {
            throw new RuntimeException("加载 JSON 配置失败", e);
        }
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.

在 application.yml 中注册 ApplicationContextInitializer:

context:
  initializer:
    classes: com.icoderoad.config.JsonPropertyContextInitializer
  • 1.
  • 2.
  • 3.

通过 @Bean 方式直接读取 JSON

另一种方式是使用 @Bean 读取 JSON 配置。

package com.icoderoad.config;


import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import java.io.IOException;


@Configuration
public class AppConfig {
    @Bean
    public JsonProperties jsonProperties() throws IOException {
        return new ObjectMapper().readValue(new ClassPathResource("configprops.json").getInputStream(), JsonProperties.class);
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.

总结

通过以上几种方法,可以轻松地使用 JSON 文件管理 Spring Boot 3.4 的应用配置。其中,使用 @PropertySource 结合 PropertySourceFactory 是最直观的方式,而 ApplicationContextInitializer 适用于更高级的自定义需求。如果你想在 Spring Boot 项目中灵活管理配置,JSON 绝对是一个高效的选择!

责任编辑:武晓燕 来源: Springboot全家桶实战案例源码
相关推荐

2025-01-13 13:47:13

2025-01-22 14:02:35

2020-12-31 11:28:09

GitLabCICD

2022-05-30 16:31:08

CSS

2025-02-08 08:00:00

JavaDeepSeekIDEA

2021-03-04 09:31:42

开源技术 项目

2019-01-15 11:40:14

开发技能代码

2025-01-08 10:35:26

代码开发者Spring

2022-06-06 12:18:44

配置可视化Nginx

2023-12-10 20:33:50

Redis搜索全文

2022-06-08 08:01:28

模板字面量类型

2024-01-30 09:21:29

CSS文字效果文字装饰

2021-08-05 16:25:37

Windows 11Windows微软

2023-04-28 15:15:39

数据库JPA

2021-09-15 08:45:55

Python文本文件代码

2021-02-03 20:19:08

Istio流量网格

2025-01-13 12:46:31

SpringBootJacksonJSON

2023-03-06 08:03:10

Python可视化工具

2025-02-07 11:32:20

2021-07-13 05:47:40

GroovyJSON软件开发
点赞
收藏

51CTO技术栈公众号