简体   繁体   中英

How to change database dynamically in Spring Boot?

How can we change database credentials and sources in Spring Boot project on run time or you can say dynamically? Let suppose if we are deploying to test server, database connection in API project point to test database, and if deploy to production server, database automatically point to production server. Do some research what kind of config we need to set these settings in our spring boot project. Technically our project will switch to more than one database connections dynamically.

How all this process will happen in Spring boot?

Let suppose if we are deploying to test server, database connection in API project point to test database, and if deploy to production server, database automatically point to production server.

There're couple of ways. The first you can provide the properties values as part of env variables. Ex:

-Ddb_url=jdbc:mysql://<server>:<port>/<databasename> -Ddb_username=root -Ddb_password=mysql

spring.datasource.url=${db_url}
spring.datasource.username=${db_username}
spring.datasource.password=${db_password}

or

You can use different properties files in accordance with different envs.

application.properties
application-test.properties
application-prod.properties

In these properties file you can pre-configured the addresses as per the profile. To activate the profile for particular env, you've to provide the following prop to springboot application. Ex:

-Dspring.profiles.active=prod

In this case, application.properties file will be used first to configured the properties and then the properties from application-prod.properties will be configured. In case of matching properties in both the files, the later file's properties will override the properties in the default property file ie application.properties .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM