方法定义

public static Properties getProperties()
  • 作用:获取当前 JVM 的系统属性集合(Properties 对象)。
  • 返回值java.util.Properties 对象(继承自 Hashtable<Object,Object>)。
  • 关键属性:包含操作系统、JVM 版本、文件编码、用户信息等(完整列表见官方文档)。

功能说明

  • 系统属性来源
    • JVM 启动时通过 -Dkey=value 传递的参数(如 -Dapp.env=production)。
    • JVM 自动收集的操作系统环境信息(如 os.nameuser.home)。
  • 常用属性: | 属性名 | 说明 | |----------------------|--------------------------| | java.version | Java 运行时版本 | | os.name | 操作系统名称 | | user.name | 当前用户 | | file.encoding | 默认文件编码 | | user.dir | 用户当前工作目录 |

示例代码

import java.util.Properties;

public class SystemPropertiesDemo {
    public static void main(String[] args) {
        // 获取所有系统属性
        Properties props = System.getProperties();
        
        // 打印所有属性 (按key排序)
        props.keySet().stream()
              .sorted()
              .forEach(key -> 
                  System.out.println(key + " = " + props.getProperty(key.toString()))
              );
        
        // 获取单个属性
        String javaVersion = System.getProperty("java.version");
        String userDir = System.getProperty("user.dir");
        
        System.out.println("\nJava Version: " + javaVersion);
        System.out.println("Current Directory: " + userDir);
        
        // 设置自定义属性(需在启动时通过 -D 传递)
        String appEnv = System.getProperty("app.env", "development"); // 默认值
        System.out.println("App Environment: " + appEnv);
    }
}

使用技巧

  1. 安全获取属性
    // 使用 getProperty(String key, String defaultValue) 避免 NullPointerException
    String path = System.getProperty("config.path", "/default/path");
    
  2. 过滤敏感信息
    • 避免直接输出所有属性(可能包含 user.password 等敏感信息)。
  3. 动态加载配置
    // 根据环境变量加载配置
    String env = System.getProperty("env", "dev");
    String configFile = "app-" + env + ".properties";
    

常见错误与注意事项

  1. 空指针风险
    // 错误写法:未处理可能的 null
    String value = System.getProperty("undefined.key").toLowerCase(); // 抛出 NPE
    
    // 正确写法:使用默认值
    String safeValue = System.getProperty("undefined.key", "").toLowerCase();
    
  2. 属性覆盖问题
    • 避免修改系统级属性(如 os.name),JVM 可能忽略或引发异常。
  3. 启动参数格式
    • -D 参数需放在主类名前:
      java -Dapp.name=MyApp -Ddebug=true MainClass # 正确
      java MainClass -Dapp.name=MyApp               # 无效(被当作程序参数)
      

最佳实践与性能优化

  1. 缓存高频属性
    public class AppConfig {
        private static final String APP_NAME = 
            System.getProperty("app.name", "DefaultApp");
    
        // 避免重复调用 getProperty()
    }
    
  2. 只读访问
    • 不要修改返回的 Properties 对象(可能影响 JVM 稳定性):
      // 危险操作!
      System.getProperties().setProperty("user.language", "zh"); // 不保证生效
      
  3. 替代方案
    • 对于容器化环境(如 Docker),优先使用环境变量(System.getenv()),而非系统属性。

总结

关键点 说明
核心用途 获取 JVM/OS 的系统配置信息
自定义属性 通过 -Dkey=value 在启动时传递
空安全 使用 getProperty(key, defaultValue) 避免 NPE
敏感信息 避免输出全部属性(可能泄露路径、用户名等)
性能 首次调用有轻微开销,建议缓存高频属性
适用场景 环境检测、路径配置、日志初始化等