Home > Net >  Spring boot: external properties file an PropertySource
Spring boot: external properties file an PropertySource

Time:08-26

I am developing a spring boot application with gradle.

I would love to tell spring where to read .properties files with a parameter. Since I am still running it via gradle, I have added this to my build.gradle

bootRun {
    args = [
            "--spring.config.additional-location=file:/path/to/my/props/folder/,file:/path/to/another/props/folder/"
    ]
}

into /path/to/my/props/folder/ I have created a file remote-connection.properties:

### remote-connection
remote.ip.address=127.0.0.1
remote.ip.port=5001

and I am trying to load those props like this

@RestController
@PropertySource("file:remote-connection.properties")
public class MyController {

    @Value("${remote.ip.address}")
    private String remoteIpAddress;
}

When i run ./gradlew bootRun i have the following error

org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [my.package.MyApplication]; nested exception is java.io.FileNotFoundException: remote-connection.properties (No such file or directory)

(I have also tried @PropertySource("classpath:remote-connection.properties") and @PropertySource("remote-connection.properties"))

It works flawlessly if I place remote-connection.properties into src/main/resources, but I want that config file to be outside the resulting jar, being able to run it with

java -jar my-application.jar --spring.config.additional-location=file:/path/to/my/props/folder/,file:/path/to/another/props/folder/

What am I missing?

Thanks in advance.

CodePudding user response:

Answering my own question.

Following this guide https://mkyong.com/spring/spring-propertysources-example/ I have changed my run args to

bootRun {
    args = [
            "--my.props.folder=/path/to/my/props/folder",
            "--my.other.props.folder=/path/to/another/props/folder",
    ]
}

and loading props like this

@RestController
@PropertySource("file:${my.props.folder}/remote-connection.properties")
@PropertySource("file:${my.other.props.folder}/some-more.properties")
public class MyController {

    @Value("${remote.ip.address}")
    private String remoteIpAddress;
}

This way, it works!!

  • Related