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 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 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 {

    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 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();
        }
    }
}

你可能感兴趣的:(spring,boot,后端,java,yaml,yml)