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");


转载于:https://my.oschina.net/guoenzhou/blog/312573

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值