栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java读取properties文件(springboot读取properties配置文件)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java读取properties文件(springboot读取properties配置文件)

获取Spring的properties文件内容

不废话,直接代码

public class PropertySpringConfig{

	private static Properties properties=new Properties();
	//获取Spring的上下文
	private static ApplicationContext applicationContext=Context.getSpringContext();
	//获取所实现的父类对象
	private static AbstractApplicationContext abstractContext=(AbstractApplicationContext) applicationContext;
	static{
		try {
			String[] postProcessorName =abstractContext.getBeanNamesForType(BeanFactoryPostProcessor.class,true,true);
			for(String ppName:postProcessorName){
				BeanFactoryPostProcessor beanProcessor=abstractContext.getBean(ppName,BeanFactoryPostProcessor.class);
				if(beanProcessor instanceof PropertyResourceConfigurer){
					PropertyResourceConfigurer propertyResourceConfigurer=(PropertyResourceConfigurer) beanProcessor;
					Method mergeProperties=PropertiesLoaderSupport.class.getDeclaredMethod("mergeProperties");
					mergeProperties.setAccessible(true);
					Properties props=(Properties)mergeProperties.invoke(propertyResourceConfigurer);
					Method converProperties=PropertyResourceConfigurer.class.getDeclaredMethod("convertProperties", Properties.class);
					converProperties.setAccessible(true);
					converProperties.invoke(propertyResourceConfigurer, props);
					properties.putAll(props);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	
	public static String getContextProperty(String keyName) {
		return properties.getProperty(keyName);
	}
}

基本的读取方法

import java.util.ResourceBundle;

public class PropertiesConfig {
	
	private static ResourceBundle resource = ResourceBundle.getBundle("config");
	
	private static ResourceBundle jobResource = ResourceBundle.getBundle("job_config");
	
	public final static String getValue(String key) {
		return resource.getString(key);
	}
	
	public final static String getValueByJob(String key) {
		return jobResource.getString(key);
	}
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/776575.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号