spring Register beans only when a property or value is specified


Example

A spring bean can be configured such that it will register only if it has a particular value or a specified property is met. To do so, implement Condition.matches to check the property/value:

public class PropertyCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        return context.getEnvironment().getProperty("propertyName") != null;
        // optionally check the property value
    }
}

In Java config, use the above implementation as a condition to register the bean. Note the use of @Conditional annotation.

@Configuration
public class MyAppConfig {

    @Bean
    @Conditional(PropertyCondition.class)
    public MyBean myBean() {
      return new MyBean();
    }
}

In PropertyCondition, any number of conditions can be evaluated. However it is advised to separate the implementation for each condition to keep them loosely coupled. For example:

@Configuration
public class MyAppConfig {

    @Bean
    @Conditional({PropertyCondition.class, SomeOtherCondition.class})
    public MyBean myBean() {
      return new MyBean();
    }
}