Configuring Multiple Environments in Spring Boot
This guide explains how to set up separate configuration files for development, testing, and production in Spring Boot, modify them for each environment, and switch between environments using configuration properties, IDE settings, or command‑line arguments.
When developing a project, you often need to handle different runtime environments such as development, testing, and production, each with its own database, Redis, and other settings. Manually changing these configurations for each release is error‑prone and time‑consuming. Spring Boot provides a simple solution for multi‑environment configuration.
1. Create configuration files for each environment
Follow Spring Boot's naming convention application-{profile}.properties , where {profile} is the environment identifier. In the resources directory create application-dev.properties , application-test.properties , and application-prod.properties for development, testing, and production respectively.
The main file application.properties holds common settings, while the profile‑specific files contain environment‑specific values.
2. Modify the configuration files
First, set a common server port in application.properties :
# Server port configuration
server.port=8088Then, add database connection details to application-dev.properties (similar changes apply to the test and prod files):
# Specify database driver
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# JDBC URL for the database
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/myapp_dev
# Database username
spring.datasource.username=root
# Database password
spring.datasource.password=rootAfter updating each profile file with the appropriate settings, the multi‑environment configuration is complete.
3. Switch between environments
The active profile can be set in three ways:
**Configuration file** – add spring.profiles.active=dev (or test , prod ) to application.properties :
# Active system profile
spring.profiles.active=dev**IDE (IntelliJ IDEA)** – configure the active profile in the Run/Debug Configuration using VM options, program arguments, or the "Active profiles" field.
**Command line** – launch the jar with the profile argument:
java -jar xxx.jar --spring.profiles.active=devWhen the application starts, Spring Boot loads the corresponding application-{profile}.properties file, as shown in the startup logs.
Conclusion
Spring Boot's multi‑environment configuration is a fundamental and essential feature, forming the basis for more advanced solutions such as Spring Cloud Config.
DataFunSummit
Official account of the DataFun community, dedicated to sharing big data and AI industry summit news and speaker talks, with regular downloadable resource packs.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.