Ever found yourself commenting out local-only configurations or using cumbersome if-else blocks for different environments? There’s a cleaner way: Spring’s @Profile annotation.
It lets you define beans that are only active when a specific profile is enabled. This is fantastic for things like mocking external services locally or using a different message broker for development versus production.
Imagine you need a local-only data source or a specific RestTemplate configuration for your integration tests:
@Configuration
public class AppConfig {
@Profile("dev")
@Bean
public MyDevService devService() {
return new MyDevServiceImpl("localhost:8080");
}
@Profile("prod")
@Bean
public MyProdService prodService() {
return new MyProdServiceImpl("prod.api.example.com");
}
}
Now, when you run your app with -Dspring.profiles.active=dev, only devService loads. For production, use prod and prodService takes over. No messy conditional logic in your code. Just distinct, well-defined configurations for each environment. Keep your builds clean and deployments predictable.
Top comments (0)