查看this question,我希望找到一种方法,可以从属性文件中将我的静态常量变量注入到应用程序中。但是我最终找到了一种方法,既能拥有蛋糕,又能吃掉它。
我在下面发布这个解决方案,以补充SO的文集...
Start with a public class named Globals (or something obvious like this)
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";
then define the property keys as private variables (for encapsulation), e.g.
private static final String DOMAIN_PACKAGE_KEY = "myapp.domain.package.name";
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.
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);
...
}
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);
}
}