nmagerko nmagerko - 1 year ago 113
Java Question

Spring Datasources based on Environment

I am trying to configure my Spring Boot application to use specific datasources when certain environmental variables exist. For example, if the

environmental variable exists, I would like to use my production datasource; otherwise, I would like to use my local datasource (of the same type).

I have found something in the Spring reference that explains how a single datasource could be declared in my
. Specifically, a MySQL datasource could look like:


However, I do not see how I could change the datasource properties conditionally in this file. Is there another way to do it?

Answer Source

In Spring Boot you can:

  1. Externalize application.properties from your jar and provide file per environment by adding path as a startup parameter:

    java -jar your-app.jar --spring.config.location=/path/to/app.properties
  2. Use Spring profiles. Create application-${profile}.properties for each profile, in each one different datasource properties

  3. Use Spring profiles and instead of application.properties, put your properties to application.yaml where you can put properties for all environments using convention as below:

        profiles: development
        port: 9001
        profiles: production
        port: 0

Learn more in the Spring Boot reference section on How to change configuration depending on the environment.