Java中如何获取spring中配置的properties属性文件内容

1.通过spring 配置properties文件

<!-- 在XML配置文件中加入外部属性文件,当然也可以指定外部文件的编码 -->
<bean id="propertyConfigurer" class="PropertyUtils">
  <property name="locations">
    <list>
     <value>classpath:shishuocms.properties</value> 
    <!-- 指定外部文件的编码 -->
    </list>
  </property>
</bean>



2.编写自定义的类PropertyUtils  继承PropertyPlaceholderConfigurer,重写processProperties 方法

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import com.shishuo.cms.exception.PropertyIsNullException;

/**
 * 属性工具类
 * 
 * @author Herbert
 * 
 */
public class PropertyUtils extends PropertyPlaceholderConfigurer {

	public static final Logger logger = Logger.getLogger(PropertyUtils.class);

	private static Map<String, String> propertyMap;

	@Override
	protected void processProperties(
			ConfigurableListableBeanFactory beanFactoryToProcess,
			Properties props) throws BeansException {
		super.processProperties(beanFactoryToProcess, props);
		propertyMap = new HashMap<String, String>();
		for (Object key : props.keySet()) {
			String keyStr = key.toString();
			String value = props.getProperty(keyStr);
			propertyMap.put(keyStr, value);
		}
	}


	public static String getValue(String name) throws PropertyIsNullException {
		String value = propertyMap.get(name);
		if (StringUtils.isBlank(value)) {
			String error = "属性[" + name + "]的值为空";
			logger.fatal(error);
			throw new PropertyIsNullException(error);
		} else {
			return value;
		}
	}

	
}



3.获取properties 参数值

String val = propertyConfigurer.getValue("oracle.url");


你可能感兴趣的:(Java中如何获取spring中配置的properties属性文件内容)