TypechoJoeTheme

香草物语

统计
登录
用户名
密码
/
注册
用户名
邮箱
输入密码
确认密码

Spring Boot动态修改刷新application.yaml文件

Laughing博主
2024-07-03
/
0 评论
/
284 阅读
/
473 个字
/
百度已收录
07/03
本文最后更新于2024年07月23日,已超过58天没有更新。如果文章内容或图片资源失效,请留言反馈,我会及时处理,谢谢!

YAML(YAML Ain't Markup Language)是一种数据序列化格式,设计用于人类阅读和编写。它在功能上类似于JSON,但在表达复杂的数据结构时更为灵活和强大。YAML 的语法简洁明了,可以轻松地表示嵌套的列表和字典。

以下是一些YAML的特点:

  1. 易于阅读:YAML 的设计使其非常易于阅读和理解。例如,使用缩进而不是括号或大括号来表示层级关系,这使得YAML文件看起来更像自然语言。
  2. 支持复杂的数据类型:YAML 可以表示复杂的嵌套数据结构,包括数组、字典和自定义类型。
  3. 可扩展性:YAML 支持自定义标签,允许你定义自己的数据类型和表示形式。
  4. 广泛的应用:YAML 被广泛用于配置文件,因为它的语法比其他格式如XML或JSON更容易编写和维护。此外,YAML 也常用于数据交换和存储。
  5. 多语言支持:YAML 有多种编程语言的库支持,包括Python、Ruby、JavaScript等,这使得在不同环境中使用YAML变得容易。

有时候我们可能在系统运行过程中,动态修改application.yaml的内容,并且在修改内容后,加载最新内容。为了修改application.yaml内容,我们可以借助snakeyaml进行修改,借助spring-cloud-contextContextRefresher实现上下文的刷新。


借助ContextRefresher刷新有个限制。
Spring Boot不能高于2.4.0版本,
因为去掉了ConfigurationBeanFactoryMetadata,否则会提示下面的报错
java.lang.ClassNotFoundException: org.springframework.boot.context.properties.ConfigurationBeanFactoryMetadata

壹、添加依赖

添加依赖的时候,一定要注意版本,版本不兼容,会出现这个报错。

<properties>
    <java.version>1.8</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <spring-boot.version>2.6.13</spring-boot.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.yaml</groupId>
        <artifactId>snakeyaml</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-context</artifactId>
        <version>2.1.2.RELEASE</version>
    </dependency>
</dependencies>

贰、增加配置文件用于测试

application.yaml

# 测试修改application.yaml
application-modify:
  name: 测试

叁、增加配置类,用于读取配置文件

ApplicationModifyConfiguration.java

package net.xiangcaowuyu.application.modify.config;

import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * description:
 *
 * @author: Laughing
 * DateTime: 2024-07-03 10:01
 */
@Component
@ConfigurationProperties(prefix = "application-modify")
@Getter
@Setter
public class ApplicationModifyConfiguration {

    private String name;

}

肆、实际修改与读取配置文件代码

package net.xiangcaowuyu.application.modify.controller;

import lombok.extern.slf4j.Slf4j;
import net.xiangcaowuyu.application.modify.config.ApplicationModifyConfiguration;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.yaml.snakeyaml.Yaml;
import javax.annotation.Resource;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;

/**
 * description:
 *
 * @author: Laughing
 * DateTime: 2024-07-03 10:05
 */
@RestController
@RequestMapping("application/yaml")
@Slf4j
public class ApplicationModifyController {

    @Resource
    private ApplicationModifyConfiguration applicationModifyConfiguration;

    @Resource
    private ContextRefresher contextRefresher;

    @GetMapping("/modify")
    @SuppressWarnings({"unchecked"})
    public void modifyApplicationYaml() throws IOException {

        String path = Objects.requireNonNull(Objects.requireNonNull(ClassUtils.getDefaultClassLoader()).getResource("application.yaml")).getPath();
        Yaml yaml = new Yaml();
        FileWriter fileWriter = null;
        try (FileInputStream fileInputStream = new FileInputStream(path)) {
            Map<String, Object> yamlMap = yaml.load(fileInputStream);
            Map<String,Object> applicationModifyMap = (Map<String, Object>) yamlMap.get("application-modify");
            applicationModifyMap.put("name", "张三");
            fileWriter = new FileWriter(path);
            fileWriter.write(yaml.dumpAsMap(yamlMap));
            fileWriter.flush();
            // 刷新配置文件
            contextRefresher.refresh();
        } catch (Exception exception) {
            log.error(exception.getLocalizedMessage());
        } finally {
            log.info("finally");
            if (fileWriter != null) {
                fileWriter.close();
            }
        }
    }

    @GetMapping("/get")
    public String getApplicationYaml() {
        // 使用刷新后的配置
        return applicationModifyConfiguration.getName();
    }

}

修改完成后,可以请求测试一下

朗读
赞(0)
赞赏
感谢您的支持,我会继续努力哒!
版权属于:

香草物语

评论 (0)