springboot 代码读取读取yml文件

本文详细介绍了一种在Spring Boot中使用YAML配置文件的方法,包括如何自定义配置加载器,以及如何在运行时动态获取和修改配置项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

配置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");

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值