返回

在原生可执行文件中使用系统属性

假设您已使用 javac 编译了以下 Java 应用程序

public class App {
    public static void main(String[] args) {
        System.getProperties().list(System.out);
    }
}

如果您使用 native-image -Dfoo=bar App 构建原生可执行文件,则系统属性 foo 将在可执行文件构建时可用。这意味着它在构建时运行的应用程序代码(通常是静态字段初始化和静态初始化器)中可用。因此,如果运行生成的执行文件,它将不会在打印的属性列表中包含 foo

另一方面,如果您使用 app -Dfoo=bar 运行可执行文件,它将在属性列表中显示 foo,因为您在可执行文件运行时指定了属性。

换句话说

  • -D<key>=<value> 作为 native-image 的参数传递,以控制构建时看到的属性。
  • -D<key>=<value> 作为原生可执行文件的参数传递,以控制运行时看到的属性。

在构建时读取系统属性

您可以在构建时读取系统属性并将它们合并到生成的执行文件中,如下例所示。

先决条件

确保您已安装 GraalVM JDK。最简单的入门方法是使用 SDKMAN!。有关其他安装选项,请访问 下载部分

  1. 将以下 Java 代码保存到名为 ReadProperties.java 的文件中,然后使用 javac 编译它
     public class ReadProperties {
         private static final String STATIC_PROPERTY_KEY = "static_key";
         private static final String INSTANCE_PROPERTY_KEY = "instance_key";
         private static final String STATIC_PROPERTY;
         private final String instanceProperty;
         static {
             System.out.println("Getting value of static property with key: " + STATIC_PROPERTY_KEY);
             STATIC_PROPERTY = System.getProperty(STATIC_PROPERTY_KEY);
         }
        
         public ReadProperties() {
             System.out.println("Getting value of instance property with key: " + INSTANCE_PROPERTY_KEY);
             instanceProperty = System.getProperty(INSTANCE_PROPERTY_KEY);
         }
            
         public void print() {
             System.out.println("Value of instance property: " + instanceProperty);
         } 
            
         public static void main(String[] args) {
             System.out.println("Value of static property: " + STATIC_PROPERTY);
             ReadProperties rp = new ReadProperties();
             rp.print();
         } 
     }
    
  2. 构建原生可执行文件,将系统属性作为命令行参数传递。然后运行原生可执行文件,在命令行上传递不同的系统属性。
     native-image -Dstatic_key=STATIC_VALUE ReadProperties
    
     ./readproperties -Dinstance_key=INSTANCE_VALUE
    

    您应该看到以下输出

     Getting value of static property with key: static_key
     Value of static property: null
     Getting value of instance property with key: instance_key
     Value of instance property: INSTANCE_VALUE
    

    这表明类静态初始化器不是在构建时运行,而是在运行时运行的。

  3. 要强制类静态初始化器在构建时运行,请使用 --initialize-at-build-time 标志,如下所示
     native-image --initialize-at-build-time=ReadProperties -Dstatic_key=STATIC_VALUE ReadProperties
    

    native-image 工具的输出中,您应该看到类似于以下内容的输出

     ...
     [1/7] Initializing...                                            (7.7s @ 0.07GB)
     Getting value of static property with key: static_key
     ...
    
  4. 再次运行可执行文件,如下所示
    ./readproperties -Dinstance_key=INSTANCE_VALUE
    

    这次您应该看到以下输出,确认静态初始化器是在构建时运行的,而不是在运行时运行的。

    Value of static property: STATIC_VALUE
    Getting value for instance property key: instance_key
    Value of instance property: INSTANCE_VALUE
    

联系我们