Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 343
nmagerko Avatar asked Dec 01 '14 17:12

nmagerko


People also ask

How do you set environment specific properties in spring boot?

Environment-Specific Properties File. If we need to target different environments, there's a built-in mechanism for that in Boot. We can simply define an application-environment. properties file in the src/main/resources directory, and then set a Spring profile with the same environment name.

What is the environment abstraction in spring?

The Environment abstraction in Spring represents the environment in which the current application is running. In the meanwhile, it tends to unify the ways to access properties in a variety of property sources, such as properties files, JVM system properties, system environment variables, and servlet context parameters.


1 Answers

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
    
  4. Use environment variables and set SPRING_DATASOURCE_URL, SPRING_DATASOURCE_USERNAME, SPRING_DATASOURCE_PASSWORD, and (optionally) SPRING_DATASOURCE_DRIVER_CLASS_NAME.

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

like image 134
Maciej Walkowiak Avatar answered Sep 20 '22 05:09

Maciej Walkowiak