Search code examples
javaspringpropertiesconfigenvironment

Spring - Getting config values from another file


I have a Spring application where in I need to access certain credentials. To keep them stored secretly, in my application.properties I only declare the path to the file where the credentials are stored. The file with the credentials themselves are stored on the machine that the application will be running on.

I somewhere, at sometime, read that it could be possible to use the following to get property values:

*(from the application.properties file...)*
example.setting1=${file:/path/to/file.properties:onevalue}
example.setting2=${file:/path/to/file.properties:another.value}
example.setting3=${file:/path/to/file.properties:a.third.value}

In code I then use org.springframework.core.env.Environment#getProperty(key) to get the property values from my application.properties. I thought this would work and return the value that is stored in the /path/to/file.properties file, but instead it returns the actual value in my application.properties, being this: example.setting1=${file:/path/to/file.properties:onevalue}.

How can I solve this and have the program return the actual credential (for example an IP "0.0.0.0") that is stored in the target file the Spring app config has the path to? Any help is very appreciated!


Solution

  • For me it fixed by adding another property value to my application.properties being spring.config.import.

    Using spring.config.import it's possible to import the files stored on the target machine and the properties in those files. For example like this: spring.config.import=file:/path/to/file.properties,file:/path/to/anotherfile.properties.

    After that, it's possible to use the same org.springframework.core.env.Environment#getProperty(key) code and get the values from the imported config files: Environment#getProperty("onevalue") and Environment#getProperty("another.value").