springboot 代码读取读取yml文件

配置config 

package com.ljzforum.platform.config;

import com.ljzforum.platform.util.CustomizedPropertyConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.util.Properties;
@Configuration
public class YmlConfig {
    @Autowired
    private Environment env;

    @Bean
    public CustomizedPropertyConfigurer ymlConfigurer() {
        System.out.println(env.getActiveProfiles()[0]);
        //1:加载配置文件
        Resource app = new ClassPathResource("application.yml");
        Resource appEnv = new ClassPathResource("application-"+env.getActiveProfiles()[0]+".yml");
        Resource oss = new ClassPathResource("oss.yml");
        Resource message = new ClassPathResource("message.yml");
        YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean();
        // 2:将加载的配置文件交给 YamlPropertiesFactoryBean
        yamlPropertiesFactoryBean.setResources(app, oss, message, appEnv);
        // 3:将yml转换成 key:val
        Properties properties = yamlPropertiesFactoryBean.getObject();
        // 4: 将Properties 通过构造方法交给我们写的工具类
        CustomizedPropertyConfigurer ymlConfigurer = new CustomizedPropertyConfigurer(properties);
        return ymlConfigurer;
    }
}

 

CustomizedPropertyConfigurer


import java.util.Properties;

public class CustomizedPropertyConfigurer {

	private static Properties ymlProperties = new Properties();

	public CustomizedPropertyConfigurer(Properties properties){
		ymlProperties = properties;
	}

	public static Object getContextProperty(String key) {
		return ymlProperties.getProperty(key);
	}
	
	public static Object setContextProperty(String key,Object value) {
		return ymlProperties.setProperty(key, value.toString());
	}

}

读取

String name = (String) CustomizedPropertyConfigurer.getContextProperty("NAME");

 

你可能感兴趣的:(springboot)