配置在.properties文件中的常量,

配置在.properties文件中的常量如何在项目中引用

一、在xml文件中使用

原文:http://blog.sina.com.cn/s/blog_7f73e06d0101642n.html


首先你先在.properties文件中以键值对的形式写好之后,在spring配置文件先将这个资源文件初始化成bean,然后再在XML中以${……}的形式取出里边的值。
在spring中的配置是:
<!-- 配置的资源文件 -->
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:/system.properties</value>
            </list>
        </property>
    </bean>

在properties文件中书写格式:
informationSerHessian.serverName = 127.0.0.1

在其他的xml中使用方式
${informationSerHessian.serverName}取出里边的值

二、在java 文件中引用

思路将.properties 的内容读取到map 中,需要的时候再使用key 取值

1.抽取公共方法( 放入map)

public class PropertyUtils {
	private static Map map = null;

	private static void loadFile() {
		map = new HashMap();
		try {
			Properties p = new Properties();
			p.load(PropertyUtils.class.getClassLoader().getResourceAsStream("bsteel.properties"));
			Iterator it = p.keySet().iterator();
			while (it.hasNext()) {
				String key = (String) it.next();
				String value = p.getProperty(key);
				map.put(key, value);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String getValue(String str) {
		if (map == null) {
			loadFile();
		}
		return (String) map.get(str);
	}
}

2、取值(map)  *.java文件内

String url = PropertyUtils.getValue("open.cbw.sms.webservice");


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值