在Java应用程序和类可见性函数中读取系统环境的最佳方法是什么?
我需要例如os.name并设计了类似
的类private String osName;
private void readSystemSettings() {
osName = System.getProperty("os.name");
}
public void printSystemSettings() {
System.out.println(this.osName);
...
}
public SystemEnvironment() {
readSystemSettings();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
获取这些信息的最佳做法是什么? 始终在启动时或仅不时调用此功能?
我想在课程实例化后尽快读出这些信息。因此构造函数调用readSystemSettings()
函数。
因为在运行期间信息总是相同的,所以我实际上只需要没有立场。意味着所有变量+函数都是最终的。或者我错了吗?
答案 0 :(得分:3)
您可以拥有一个类,其中所有变量都标记为final,然后在静态块中初始化。
public class SystemProperties{
public static final String OS_NAME;
// other properties
static{
OS_NAME = System.getProperty("os.name");
// initialize other properties
}
}
否则,如果您处于Spring或EJB等托管环境中,则可以将SystemProperties
标记为singleton
,并在使用@PostContruct
注释的方法中初始化变量。
public class SystemProperties{
public static String OS_NAME;
// other properties
@PostConstruct
private void init(){
OS_NAME = System.getProperty("os.name");
// initialize other properties
}
}
答案 1 :(得分:0)
您可以使用实用程序类:
public final class Utilities {
public static final String OS_NAME = System.getProperty("os.name");
private Utilities() { } // utility classes can't be instantiated
}
这样,在应用程序启动期间,此属性只会初始化一次。然后,您可以使用Utilities.OS_NAME
从代码中的任何位置访问此媒体资源。
答案 2 :(得分:0)
由于该值是全局设置的,您可以执行
enum SystemEnvironment {
;
public static final String OS_NAME = System.getProperty("os.name");
或者你每次都可以看一下,因为你不应该经常打电话。
enum SystemEnvironment {
;
public static getOsName() {
return System.getProperty("os.name");
}
如果您经常使用它,我建议为它创建一些测试。
enum SystemEnvironment {
;
public static final boolean IS_WINDOWS = getOsName().startsWith("Window");
public static getOsName() {
return System.getProperty("os.name");
}
答案 3 :(得分:0)
您可以使用OWNER库。
OWNER API是一个Java库,其目标是最小化通过Java属性文件处理应用程序配置所需的代码。
所以要加载属性,你应该像这样创建类
public interface MyConfig extends Config {
@Key("os.name")
String osName();
}
然后您可以在需要时加载配置:
ServerConfig cfg = ConfigFactory.create(MyConfig.class,
System.getProperties(),
System.getenv()
);
System.out.println("Os name:" + cfg.osName());
有关详细信息,请参阅文档http://owner.aeonbits.org/docs/usage/