Java 如何为一组常量提供多个配置文件,以便轻松地从一个常量切换到另一个常量?
我需要维护一个string&int常量文件来声明应用程序的配置参数。为了获得良好的性能,我在一个简单的java类中将它们声明为Java 如何为一组常量提供多个配置文件,以便轻松地从一个常量切换到另一个常量?,java,Java,我需要维护一个string&int常量文件来声明应用程序的配置参数。为了获得良好的性能,我在一个简单的java类中将它们声明为静态final常量。但现在我意识到,我也应该能够拥有多个这样的配置文件&轻松地从一个配置文件切换到另一个配置文件。现在我有这样的文件: public final class Config { public static final String A1="..."; public static final String A2="...";
静态final
常量。但现在我意识到,我也应该能够拥有多个这样的配置文件&轻松地从一个配置文件切换到另一个配置文件。现在我有这样的文件:
public final class Config {
public static final String A1="...";
public static final String A2="...";
...
public static final String AN="...";
}
要使用任何配置参数,我只需这样使用:config.A1
这些参数在应用程序中大量使用,因此我希望能够以良好的性能直接访问字段(而不是通过getter方法)
但是我应该如何维护多个这样的配置文件&允许轻松地从一个切换到另一个
public final class Config {
public static final String A1;
public static final String A2;
...
public static final String AN;
static
{
Properties props = new Properties ();
try
{
props.load (new FileInputStream (System.getProperty ("config.file")));
}
catch (IOException ex)
{
throw new RuntimeException (ex);
}
A1 = props.getProperty ("A1");
A2 = props.getProperty ("A2");
...
AN = props.getProperty ("AN");
}
}
然后,您可以使用系统属性
config.file
指定要使用的配置文件。使用属性文件。存储系统属性中应使用的属性文件
这是一个你如何做到这一点的例子。您应该使用单例而不是静态方法,并且应该保持ResourceBundle的加载状态,而不是每次都加载属性文件。这只是一个例子
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class Config {
//Stores the currently used property file
private static String route;
public static String getRoute() {
return route;
}
public static void setRoute(String route) {
this.route = route;
}
//Read a value from a properties file.
//Mikhail Vladimirov wrote another way of doing it, so this is just an example of another way of doing it.
private static String fetchTextFrom(String key, String route) {
String text = null;
try {
ResourceBundle bundle = ResourceBundle.getBundle(route);
text = bundle.getString(key);
} catch (MissingResourceException mre) {
text = key;
}
return text;
}
//Read a value from the current properties file
public static String fetchText(String key) {
return fetchTextFrom(key, getRoute());
}
}
你可以使用反射。这里有一些参考资料-非常感谢!是否有任何特定的格式,必须根据这些格式将参数写入config.file中。您能指出关于如何编写config.file的指南中的任何链接吗?@user01在我的示例中,它应该是Java属性文件,如下所述: