springboot优雅的获取yml配置(区分生产环境和测试环境)

#首先配置Bean

import com.vivo.admin_log.common.utils.YamlConfigurerUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.util.Properties;

/**
 * @author 72038611
 */
@Configuration
public class BeanConfiguration {
    private final Logger logger = LoggerFactory.getLogger(BeanConfiguration.class);
    @Bean
    public YamlConfigurerUtil ymlConfigurerUtil() {
        //1:加载配置文件
        Resource app = new ClassPathResource("config/application.yml");
        Resource appDev = new ClassPathResource("config/application-dev.yml");
        Resource appProd = new ClassPathResource("config/application-prod.yml");
        YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean();
        // 2:将加载的配置文件交给 YamlPropertiesFactoryBean
        yamlPropertiesFactoryBean.setResources(app);
        // 3:将yml转换成 key:val
        Properties properties = yamlPropertiesFactoryBean.getObject();
        String active = properties.getProperty("spring.profiles.active");
        if (active == "" || active == null) {
            logger.error("未找到spring.profiles.active配置!");
        }else {
            //判断当前配置是什么环境
            if ("dev".equals(active)) {
                yamlPropertiesFactoryBean.setResources(app,appDev);
            }else if("prod".equals(active)){
                yamlPropertiesFactoryBean.setResources(app,appProd);
            }
        }
        // 4: 将Properties 通过构造方法交给我们写的工具类
        YamlConfigurerUtil ymlConfigurerUtil = new YamlConfigurerUtil(yamlPropertiesFactoryBean.getObject());
        return ymlConfigurerUtil;
    }
}

#工具类

import java.util.Properties;

/**
 * @author 72038611
 */
public class YamlConfigurerUtil {
    private static Properties ymlProperties = new Properties();
 
    public YamlConfigurerUtil(Properties properties){
        ymlProperties = properties;
    }
 
    public static String getStrYmlVal(String key){
        return ymlProperties.getProperty(key);
    }
 
    public static Integer getIntegerYmlVal(String key){
        return Integer.valueOf(ymlProperties.getProperty(key));
    }
}

改编自https://blog.csdn.net/xiao______xin/article/details/86700939#comments

你可能感兴趣的:(工具类)