Search code examples
spring-bootdocker-composeapplication.properties

Provide dynamic values to Spring application.properties and to docker


How can we provide the dynamic values to Application.properties or Application-dev.properties in spring-boot and docker-compose?

I checked other places but I didn't understood how and when the dynamic values are assigned to those files? will it be possible with a example to get it done?

These are the properties in my Application.properties

spring.datasource.url=jdbc:postgresql://postgres:5432/test
spring.datasource.username=admin
spring.datasource.password=admin
spring.jpa.database=POSTGRESQL

is it possible to give that username, password or database name "test" dynamically via some docker or some frontend and update my application.properties accordingly? and also how it is possible when using Application-dev.properties


Solution

  • I think you could use environment variables for this you can add them in your project's configuration, like this :

    environtment variable are key value pair where you could use keys in application.properties and value are value that you want:

    HOST=your_host,PORT=your_port,DB=database_name,USER=username,PASS=password
    

    application.properties:

    spring.datasource.url=jdbc:postgresql://${HOST}:${PORT}/${DB}
    spring.datasource.username=${USER}
    spring.datasource.password=${PASS}
    

    for using application-dev you can also create environment variable for this like ENV=dev and in application.properties use ENV like this:

    spring.profiles.active=${ENV}
    

    also when you deploy this app on cloud or container there is option for providing environment variable so you can provide it.