Springboot - 打印多个yml最终合并配置信息

Springboot项目中多个yml配置优先级和最终配置容易混淆,本文帮助打出yml优先级和最终配置,以yml格式打印到控制台,便于开发调试。

一、服务启动后打印

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.common.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.context.properties.source.ConfigurationPropertySources;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

@Slf4j
@Component
public class ConfigurationPrinter implements ApplicationRunner {

    @Autowired
    private ConfigurableApplicationContext applicationContext;

    public void printMergedConfiguration() {
        ConfigurableEnvironment environment = applicationContext.getEnvironment();
        StringBuffer yamlFileNames= new StringBuffer("bootstrap.yml\n");
        environment.getPropertySources().stream().forEach(propertySource -> {
            if(propertySource.getName().contains("bootstrapProperties")){
                yamlFileNames.append(StringUtils.substringAfter(propertySource.getName(),"bootstrapProperties-")+"\n");
            }
        });
        log.info("\n************** Configuration files priority **************\n" + yamlFileNames.toString());
        ConfigurationPropertySources.attach(environment);
        Binder binder = Binder.get(environment);
        Map<String, Object> properties = binder.bind("", Map.class).orElse(null);
        properties.remove("java");
        properties.remove("sun");
        properties.remove("jboss");
        properties.remove("catalina");
        properties.entrySet().stream().sorted(Map.Entry.comparingByKey());
        Map<String, Object> sortedProperties = new LinkedHashMap<>();
        properties.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByKey())).forEachOrdered(x -> sortedProperties.put(x.getKey(), x.getValue()));
        printYaml(JsonUtils.toString(sortedProperties));
    }

    @Override
    public void run(ApplicationArguments args) {
        printMergedConfiguration();
    }

    private void printYaml(String json){
        try {
            ObjectMapper jsonMapper = new ObjectMapper();
            Object jsonObject = jsonMapper.readValue(json, Object.class);

            ObjectMapper yamlMapper = new ObjectMapper(new YAMLFactory());
            String yaml = yamlMapper.writeValueAsString(jsonObject);
            log.info("\n************** All configs **************\n" + yaml);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

二、监听事件打印

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.common.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.SpringApplicationEvent;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.context.properties.source.ConfigurationPropertySources;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.Map;

@Slf4j
@Component
public class ConigurationPrinterEvent implements ApplicationListener<SpringApplicationEvent> {

    private static int printCount = 0;

    private final ConfigurableApplicationContext applicationContext;

    @Autowired
    public ConigurationPrinterEvent(ConfigurableApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public void onApplicationEvent(SpringApplicationEvent event) {
        if (printCount == 0) {
            Environment environment = applicationContext.getEnvironment();
            ConfigurationPropertySources.attach(environment);
            Binder binder = Binder.get(environment);
            Map<String, Object> properties = binder.bind("", Map.class).orElse(null);
            printYaml(JsonUtils.toString(properties));
        }
    }

    private void printYaml(String json) {
        try {
            ObjectMapper jsonMapper = new ObjectMapper();
            Object jsonObject = jsonMapper.readValue(json, Object.class);

            ObjectMapper yamlMapper = new ObjectMapper(new YAMLFactory());
            String yaml = yamlMapper.writeValueAsString(jsonObject);
            log.info("\n************** Print all configs **************\n" + yaml);
            printCount++;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以在Spring Boot应用程序中使用多个YAML文件。以下是如何完成的: 1. 创建多个YAML文件,例如application-dev.yml和application-prod.yml。 2. 在application.yml文件中,使用以下格式引用其他YAML文件: ```yaml spring: profiles: active: dev --- spring: profiles: dev include: - application-dev.yml --- spring: profiles: prod include: - application-prod.yml ``` 在这个例子中,我们定义了一个名为“dev”的配置文件,并将其设置为活动配置文件。然后,我们使用“include”关键字引用了application-dev.yml文件。同样,我们定义了一个名为“prod”的配置文件,并使用“include”关键字引用了application-prod.yml文件。 3. 在application-dev.yml和application-prod.yml文件中,您可以定义与所需环境相关的配置属性。 例如,在application-dev.yml中,您可以定义以下属性: ```yaml server: port: 8080 logging: level: root: debug ``` 在application-prod.yml中,您可以定义以下属性: ```yaml server: port: 80 logging: level: root: info ``` 在这个例子中,我们定义了不同的端口和日志级别,以适应不同的环境。 4. 根据需要切换配置文件。例如,如果要将应用程序部署到生产环境中,则可以将活动配置文件更改为“prod”。 您可以使用以下命令更改活动配置文件: ```shell java -jar myapp.jar --spring.profiles.active=prod ``` 这将使应用程序使用application-prod.yml中定义的属性。 通过使用多个YAML文件,您可以轻松地为不同的环境定义不同的属性,并根据需要切换配置文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值