Video in progress

Strong Middle 🌱 Spring

What's the difference between @Profile and @ConditionalOnProperty, and which is better for turning a feature on and off?

@Profile ties a bean to an environment name (dev, prod); @ConditionalOnProperty ties it to a specific setting. For toggling a feature, @ConditionalOnProperty is handier: it doesn't depend on the environment, you can see what's enabled, and it's easy to control in tests.

📖 Answer

@Bean
@Profile("prod")
SmsSender realSms() { ... }          // "if prod, real SMS"

@Bean
@ConditionalOnProperty(name = "sms.enabled", havingValue = "true")
SmsSender realSms() { ... }          // "if SMS is enabled"

If you tie it to a profile, one day you'll need real SMS on staging too. Now it's @Profile({"prod", "staging"}) — the profile lists keep growing and "what runs in which environment" ends up scattered all over the code.

It usually ends up like this:

  • a profile only picks a set of settings (application-prod.yml);
  • beans are tied to explicit flags;
  • the profile files set the flags:
# application-prod.yml
sms:
  enabled: true

Watch matchIfMissing: with @ConditionalOnProperty(name = "sms.enabled", havingValue = "true", matchIfMissing = false), if the setting is missing, the bean isn't created. Features that move money or send real messages should be off by default.

Feature flags that flip at runtime without a restart are a different story — for those you need a separate system like Unleash, LaunchDarkly or a table in the database.