获取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);
}
}