How to reference a system property within a user-defined .properties file?

后端 未结 3 755
别那么骄傲
别那么骄傲 2020-12-19 03:07

I want to define a property for a working directory(say work.dir=/home/username/working-directory), for my production .properties file, without hard-coding the

相关标签:
3条回答
  • 2020-12-19 03:24

    Get the property from the file, then replace supported macros.

    String propertyValue = System.getProperty("work.dir");
    String userHome = System.getProperty("user.home" );
    String evaluatedPropertyValue = propertyValue.replace("$user.home", userHome );
    
    0 讨论(0)
  • 2020-12-19 03:24

    You can manage your properties with Commons Configuration and use Variable Interpolation

    If you are familiar with Ant or Maven, you have most certainly already encountered the variables (like ${token}) that are automatically expanded when the configuration file is loaded. Commons Configuration supports this feature as well[...]

    That would allow a .properties file with

    work.dir=${user.home}/working-directory
    
    0 讨论(0)
  • 2020-12-19 03:33

    This feature is not available in java.util.Properties. But many libraries add variable substitution to properties.

    Here an example of what you are trying to do using OWNER API library (see paragraph "importing properties"):

    public interface SystemPropertiesExample extends Config {
        @DefaultValue("Welcome: ${user.name}")
        String welcomeString();
    
        @DefaultValue("${TMPDIR}/tempFile.tmp")
        File tempFile();
    }
    
    SystemPropertiesExample conf =
            ConfigFactory.create(SystemPropertiesExample.class, System.getProperties(), System.getenv());
    String welcome = conf.welcomeString();
    File temp = conf.tempFile();
    
    0 讨论(0)
提交回复
热议问题