在Java中将属性文件中的属性作为静态常量使用

3
如何使用属性文件存储应用程序中的全局变量,并使用公共静态常量变量将它们注入到应用程序中?
查看this question,我希望找到一种方法,可以从属性文件中将我的静态常量变量注入到应用程序中。但是我最终找到了一种方法,既能拥有蛋糕,又能吃掉它。
我在下面发布这个解决方案,以补充SO的文集...

2
请先在您的问题中添加更多细节,不要只是链接另一个问题。 - Sotirios Delimanolis
谢谢,我已经编辑了帖子,使其更具问题性 :) - coderatchet
1个回答

4
我的解决方案涉及全局变量的概念(这似乎是不好的),所以如果你有胆量,请继续阅读。
我相信,尽管我们希望遵循函数式编程的潮流,并从我们的函数中删除所有“拉动”依赖的概念,但有些真理需要绝对的基础,因此一些形式的全局变量作为源头是有帮助的。在运行时应用中,但我不想引发争论...

解决方案

  1. Start with a public class named Globals (or something obvious like this)

  2. To Inject a property from a property file you need to establish the basename (or location) of the properties file, e.g. "com.example.myapp.core.configuration" may represent a configuration file in your core module with a physical url of jar:file:C:/jars/myapp.ear/core.jar!/com/example/myapp/core/configuration.properties. make this basename a static final variable:

    public static final String CORE_CONFIGURATION_BASENAME = "com.example.myapp.core.configuration";
    
  3. then define the property keys as private variables (for encapsulation), e.g.

    private static final String DOMAIN_PACKAGE_KEY = "myapp.domain.package.name";
    
  4. then define the property themself as a public final static variable, like so:

    public static final String DOMAIN_PACKAGE; //we leave it uninitialized on purpose.
    
  5. the above code will throw a compiler error when built, so we need to initialize it using the static block. to do this, we must first retrieve the resource bundle using the basename we defined:

    static {
        ResourceBundle bundle = PropertyResourceBundle(CORE_CONFIGURATION_BASENAME);
        ...
    }
    
  6. then we assign the final properties using the keys we define:"

    static {
        ResourceBundle bundle = PropertyResourceBundle(CORE_CONFIGURATION_BASENAME);
        DOMAIN_PACKAGE = bundle.getString(DOMAIN_PACKAGE_KEY);
    }
    

就是这样。这将在加载Globals类时初始化,因此如果您更改配置属性的值并希望它们反映在应用程序中,您需要重新启动应用程序以强制类加载器重新加载类。

总之:

package com.example.myapp.core.util;

import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

public class Globals {
    public static final String CORE_CONFIGURATION_BASENAME = "com.example.myapp.core.configuration";
    private static final String DOMAIN_PACKAGE_KEY = "myapp.domain.package.name";
    public static final String DOMAIN_PACKAGE; //we leave it uninitialized on purpose.

    static {
        ResourceBundle bundle = PropertyResourceBundle(CORE_CONFIGURATION_BASENAME);
        DOMAIN_PACKAGE = bundle.getString(DOMAIN_PACKAGE_KEY);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接