获取Spring的properties文件内容

获取Spring的properties文件内容

不废话,直接代码

/**
 * 此类为获取config.properties的文件内容,根据Spring进行获取
 *  也可以使用 PropertiesConfig 这个类类读取配置文件
 *  PropertiesConfig只能读取
 * @author xxyf55
 *
 */
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();
		}
		
	}

	/**
	 * 根据keyName获取.property文件中的value
	 * @param keyName key
	 * @return value
	 */
	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);
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值