Video in progress

Strong Middle 🌱 Spring

How do you use @Conditional to create a bean under your own condition?

The ready-made conditions are usually enough: @ConditionalOnProperty, @ConditionalOnClass, @ConditionalOnBean. For more complex logic, you write a Condition implementation and add @Conditional(MyCondition.class).

📖 Answer

The most common need is switching a feature on and off with a setting:

@Bean
@ConditionalOnProperty(prefix = "sms", name = "provider", havingValue = "eskiz")
SmsSender eskizSender(EskizProperties p) { return new EskizSmsSender(p); }

@Bean
@ConditionalOnMissingBean(SmsSender.class)
SmsSender logSender() { return new LoggingSmsSender(); } // if none of the others is chosen

Your own condition:

class OnLinuxCondition implements Condition {
    @Override
    public boolean matches(ConditionContext ctx, AnnotatedTypeMetadata md) {
        return System.getProperty("os.name").toLowerCase().contains("linux");
    }
}

@Bean
@Conditional(OnLinuxCondition.class)
DiskWatcher diskWatcher() { ... }

@ConditionalOnBean is unreliable in ordinary configuration: it only sees the beans registered up to that point. Use it mainly inside auto-configurations.

When conditions pile up, it gets hard to understand which bean was created and why. Write a test for every conditional bean; ApplicationContextRunner makes that easy:

new ApplicationContextRunner().withUserConfiguration(SmsConfig.class)
    .withPropertyValues("sms.provider=eskiz")
    .run(ctx -> assertThat(ctx).hasSingleBean(EskizSmsSender.class));