Java中的资源绑定

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/G0_hw/article/details/83012172

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

猜你喜欢

转载自blog.csdn.net/G0_hw/article/details/83012172