栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何从硬编码的静态配置文件切换到.properties文件?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何从硬编码的静态配置文件切换到.properties文件?

这是我过去使用过的一段代码-可以适应您的示例:

public enum Configuration {    PROPERTY1("property1.name", "default_value_1"),    PROPERTY2("property2.name", "default_value_2");    private final String key;    private String defaultValue;    Configuration(String key) {        this(key, NA);    }    Configuration(String key, String defaultValue) {        this.key = key;        this.defaultValue = defaultValue;    }    private final static Logger logger = LoggerFactory.getLogger(Configuration.class);    private final static String NA = "n.a.";    private final static String CONFIG_FILE = "properties/config.properties";    private final static String NOT_A_VALID_KEY = "Not a valid property key";    private final static Map<Configuration, String> configuration = new EnumMap<>(Configuration.class);    static {        readConfigurationFrom(CONFIG_FILE);    }    private static void readConfigurationFrom(String fileName) {        logger.info("Reading resource: {}", fileName);        try (InputStream resource = Configuration.class.getClassLoader().getResourceAsStream(fileName);) { Properties properties = new Properties(); properties.load(resource); //throws a NPE if resource not founds for (String key : properties.stringPropertyNames()) {     configuration.put(getConfigurationKey(key), properties.getProperty(key)); }        } catch (IllegalArgumentException | IOException | NullPointerException e) { logger.error("Error while reading the properties file {}", fileName, e); populateDefaultValues();        }    }    private static Configuration getConfigurationKey(String key) {        for (Configuration c : values()) { if (c.key.equals(key)) {     return c; }        }        throw new IllegalArgumentException(NOT_A_VALID_KEY + ": " + key);    }    private static void populateDefaultValues() {        for (Configuration c : values()) { configuration.put(c, c.defaultValue);        }    }        public String get() {        return configuration.get(this);    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/464276.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号