Spring Boot Externalize properties from within application.properties

Viewed 777

I want to set my property source location to point to an external directory from within application.propoerties itself. I know passing command line argument as follows does the job.

java -jar myApp.jar --spring.config.location=/Users/tony/Desktop/override.properties

But I want to set this path from within the application itself rather than passing a command-line argument. I tried adding spring.config.location=/Users/tony/Desktop/override.properties to my application.properties but it doesn't work.

How can I do this?

2 Answers

You can try adding the following annotation to your main class where you call SpringApplication.run() :

@PropertySource("/Users/tony/Desktop/override.properties")

On running the SpringBoot application, it should pick up the properties from there. Excluding the application.properties from src/main/resources using build - resources - resource - excludes - exclude in pom.xml would help to ensure that the packaged jar doesn't include the applcation.properties and would force Spring Boot to pick it up from path specified in @PropertySource

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
            <excludes>
                <exclude>**/application.properties</exclude>
            </excludes>
        </resource>
    </resources>
</build>

But keep in mind that in this way, you are creating tight coupling of your properties file with your application. If you keep it as a runtime argument, it would be having enough flexibility to run elsewhere and maintenance would be easier too.

spring.config.location and spring.config.additional-location are only useful when set as Environment Variable, System Property, or command line argument.

The best you can do to specify additional configuration files to be loaded directly in your application.properties file, is to set the spring.config.import property like so:

spring.config.import=file:/Users/tony/Desktop/override.properties

References: https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config-files

Related