nmagerko nmagerko - 7 months ago 64
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

MY_PROD_DATASOURCE
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
application.properties
. Specifically, a MySQL datasource could look like:

spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driverClassName=com.mysql.jdbc.Driver


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

Answer

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:

    spring:
        profiles: development
    server:
        port: 9001
    
    ---
    
    spring:
        profiles: production
    server:
        port: 0
    

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