Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

java - How can I provide different database configurations with Spring Boot?

As I currently see it I have 5 possible database profiles

  • CI testing -> h2 mem
  • developer environment (could be test or app run) -> h2 mem, or h2 file, or postgres
  • production -> postgres (ideally credentials not stored in the git/war)

currently I have postgres configured for running the application, and h2 configured for testing via having a different application.properties in java/resources vs test/resources

what's the simplest way to have the database connection information change for these scenarios?

question from:https://stackoverflow.com/questions/28007686/how-can-i-provide-different-database-configurations-with-spring-boot

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As M. Deinum mentions in his comment, the simplest way to do this is to use profile specific configuration.

Spring Boot allows you to have one common configuration file (application.properties) and then multiple other files, each specific to a profile (application-${profile}.properties).

For instance:

  • application.properties - Common configuration
  • application-dev.properties - Configuration for dev profile
  • application-ci.properties - Configuration for ci profiles

If your application runs with "ci" profile for instance, the default configuration file as well as the ci configuration file (which would contain the datasource configuration properties for ci profile) will be loaded.

To switch profiles you can use one of the following options:

  • JVM property: -Dspring.profiles.active=ci
  • Command line switch: --spring.profiles.active=dev

For unit tests you can use @ActiveProfiles("test") annotation on your test classes to tell Spring that unit tests should be run with test profile.

Also if you don't want to store production database credentials along with your source code, you can specify external configuration file when you deploy your app in production:

  • Using command line switch: --spring.config.location=/srv/myapp/config.properties
  • Using a JVM property: -Dspring.config.location=/srv/myapp/config.properties

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...