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

来源:互联网 发布:js attribute property 编辑:程序博客网 时间:2024/06/06 00:37

配置在.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 0