Java中的资源绑定

1.java.util.ResourceBundle

package com.h.util;

import java.io.UnsupportedEncodingException;
import java.util.Locale;
import java.util.ResourceBundle;

/**
 * 属性文件读取器
 */
public class GetPropertiesVal {

    //该对象不支持实例化
    private GetPropertiesVal(){}

    /**
     * java.util.ResourceBundle类使用的限制:只能处理特定的文件类型: .properties
     */
    private static ResourceBundle resourceBundle;

    /**
     * 资源的静态绑定,在编译期绑定资源,程序启动会检查
     * 要绑定的资源是否存在,如果不存在会报错
     */
    static {
        resourceBundle = ResourceBundle.getBundle("config", Locale.getDefault());
    }

    public static String getLabel(String key) {
        String label;
        try {
            label = new String(resourceBundle.getString(key).getBytes("ISO-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        return label;
    }
}
    public static void main(String[] args) throws Exception {
        /**
         * 在Resources资源包下存在config.properties
         */
        String label = GetPropertiesVal.getLabel("fn.api.shop.url");
        System.out.println(label);
    }

关于Java中的静态绑定和动态绑定:http://www.importnew.com/14338.html

2.动态绑定
上面实现的是资源的静态绑定,但现在我有多个配置文件,每个配置文件对应不同的端(如APP端和微信端),如何实现资源的动态绑定呢?

package com.h.util;

import java.io.UnsupportedEncodingException;
import java.util.Locale;
import java.util.ResourceBundle;

/**
 * 属性文件读取器
 */
public class GetPropertiesVal {

    private ResourceBundle resourceBundle;

    public GetPropertiesVal(String propertiesHolder){
        this.resourceBundle = ResourceBundle.getBundle(propertiesHolder, Locale.getDefault());;
    }

    public String getLabel(String key) {
        String label;
        try {
            label = new String(resourceBundle.getString(key).getBytes("ISO-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        return label;
    }
}
package com.h.util;

/**
 * App端属性配置常量类,绑定到类路径下app_config.properties资源
 */
public class AppPropConstants {
    private static GetPropertiesVal getPropertiesVal = new GetPropertiesVal("app_config");

    public static final String MY_PROP = getPropertiesVal.getLabel("myProp");
}

package com.h.util;

/**
 * 微信端属性配置常量类,绑定到类路径下wx_config.properties资源
 */
public class WxPropConstants {
    private static GetPropertiesVal getPropertiesVal = new GetPropertiesVal("wx_config");
    public static final String MY_PROP = getPropertiesVal.getLabel("myProp");
}
    public static void main(String[] args) throws Exception {
        System.out.println(AppPropConstants.MY_PROP);
        System.out.println(WxPropConstants.MY_PROP);
    }

3.扩展ResourceBandle实现XML资源捆绑

package com.h.util;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

public class XMLResourceBundleControl extends ResourceBundle.Control {
    private static String XML = "xml";

    @Override
    public List<String> getFormats(String baseName) {
        return Collections.singletonList(XML);
    }

    @Override
    public ResourceBundle newBundle(String baseName, Locale locale, String format,
                                    ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException,
            IOException {

        if ((baseName == null) || (locale == null) || (format == null) || (loader == null)) {
            throw new NullPointerException();
        }
        ResourceBundle bundle = null;
        if (!format.equals(XML)) {
            return null;
        }

        String bundleName = toBundleName(baseName, locale);
        String resourceName = toResourceName(bundleName, format);
        URL url = loader.getResource(resourceName);
        if (url == null) {
            return null;
        }
        URLConnection connection = url.openConnection();
        if (connection == null) {
            return null;
        }
        if (reload) {
            connection.setUseCaches(false);
        }
        InputStream stream = connection.getInputStream();
        if (stream == null) {
            return null;
        }
        BufferedInputStream bis = new BufferedInputStream(stream);
        bundle = new XMLResourceBundle(bis);
        bis.close();
        return bundle;
    }

    /**
     * XML配置文件读取工具
     */
    private static class XMLResourceBundle extends ResourceBundle {
        private Properties props;

        XMLResourceBundle(InputStream stream) throws IOException {
            props = new Properties();
            props.loadFromXML(stream);
        }

        @Override
        protected Object handleGetObject(String key) {
            return props.getProperty(key);
        }

        @Override
        public Enumeration<String> getKeys() {
            Set<String> handleKeys = props.stringPropertyNames();
            return Collections.enumeration(handleKeys);
        }
    }
}

application.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <entry key="name">wanghong</entry>
</properties>
package com.h.util;

import java.io.UnsupportedEncodingException;
import java.util.ResourceBundle;

/**
 * XML文件读取器
 */
public class GetPropertiesVal {

    private ResourceBundle resourceBundle;

    public GetPropertiesVal(String propertiesHolder){
        this.resourceBundle = ResourceBundle.getBundle(propertiesHolder,new XMLResourceBundleControl());;
    }

    public String getLabel(String key) {
        String label;
        try {
            label = new String(resourceBundle.getString(key).getBytes("ISO-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        return label;
    }
}
    public static void main(String[] args) throws Exception {
        GetPropertiesVal getPropertiesVal = new GetPropertiesVal("application");
        System.out.println(getPropertiesVal.getLabel("name"));
    }

参考:http://rqzhou.iteye.com/blog/1036532

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值