What are Profiles in Spring Boot
In Spring Boot, Profiles are a powerful feature that allows you to define different configurations for different environments (e.g., development, testing, production). This helps in managing environment-specific properties and beans without changing the codebase.
Profile Activation: You can activate a profile in several ways:
--spring.profiles.active=dev
application.properties
or application.yml
file:
spring.profiles.active=dev
SPRING_PROFILES_ACTIVE=dev
Profile-Specific Configuration: You can create profile-specific configuration files:
application-dev.properties
application-test.properties
application-prod.properties
Spring Boot will automatically load the properties from the active profile's configuration file.
Conditional Beans: You can define beans that are only loaded when a specific profile is active using the @Profile
annotation:
@Configuration
@Profile("dev")
public class DevConfig {
// Beans specific to the development environment
}
Multiple Profiles: You can activate multiple profiles at once, separated by commas:
spring.profiles.active=dev,featureX
Default Profile: You can set a default profile that will be used if no other profile is activated:
spring.profiles.default=dev
Creating Profile-Specific Properties:
application-dev.properties
:
server.port=8081
spring.datasource.url=jdbc:mysql://localhost:3306/dev_db
application-prod.properties
:
server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/prod_db
Using Profiles in Code:
@RestController
public class MyController {
@Value("${my.property}")
private String myProperty;
@GetMapping("/property")
public String getProperty() {
return myProperty;
}
}
Activating a Profile: You can run your Spring Boot application with a specific profile using:
mvn spring-boot:run -Dspring-boot.run.profiles=dev
In summary, Spring Profiles provide a convenient way to manage different configurations and beans for various environments, making it easier to develop, test, and deploy applications.