获取Spring的properties文件内容
不废话,直接代码
public class PropertySpringConfig{
private static Properties properties=new Properties();
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);
}
}
|