Spring Boot allows developers to easily manage different environments (e.g., development, testing, production) by using profiles. This feature enables externalized configuration, making it easier to adjust settings for different stages of the application lifecycle without modifying the code.
Profiles in Spring Boot allow you to group beans and configurations based on the environment in which the application is running. For example, you may have different database credentials for development and production. Spring Boot allows you to activate these profiles through the application.properties
or application.yml
files.
Define Profiles
You can define profiles in your configuration files in two common formats: properties or YAML.
Using application.properties
You can define a profile by specifying properties for each environment in different files. For example:
- application.properties (common/default configurations):
1 |
spring.application.name=MyApp |
- application-dev.properties (development profile):
1 2 3 |
spring.datasource.url=jdbc:mysql://localhost:3306/dev_db spring.datasource.username=dev_user spring.datasource.password=dev_pass |
- application-prod.properties (production profile):
1 2 3 |
spring.datasource.url=jdbc:mysql://prod_db_host:3306/prod_db spring.datasource.username=prod_user spring.datasource.password=prod_pass |
To activate a specific profile, you can set the spring.profiles.active
property:
1 |
spring.profiles.active=dev |
Using application.yml
YAML files provide a cleaner way to organize your configurations.
-
application.yml (common/default configurations):
1 2 3 |
spring: application: name: MyApp |
- application-dev.yml (development profile):
1 2 3 4 5 |
spring: datasource: url: jdbc:mysql://localhost:3306/dev_db username: dev_user password: dev_pass |
- application-prod.yml (production profile):
1 2 3 4 5 |
spring: datasource: url: jdbc:mysql://prod_db_host:3306/prod_db username: prod_user password: prod_pass |
Use Profiles in Code
You can conditionally enable beans or configuration classes based on active profiles. Use the @Profile
annotation to bind beans to specific profiles:
1 2 3 4 5 |
@Configuration @Profile("dev") public class DevConfig { // Development-specific beans } |
Similarly, in your application class, you can check which profile is active:
1 2 3 4 5 6 |
@SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } |