Dimitrios Efthymiou
Dimitrios Efthymiou

Reputation: 585

Can we declare spring bean conditionally?

Is there a way we can declare a Spring bean conditionally like:

<bean class="path.to.the.class.MyClass" if="${1+2=3}" />

It would be useful instead of having to use profiles. I don't have a specific use-case in mind, but it came to me.

Upvotes: 37

Views: 48469

Answers (2)

Sundararaj Govindasamy
Sundararaj Govindasamy

Reputation: 8495

You can use @Conditional from Spring4 or @ConditionalOnProperty from Spring Boot.

  1. Using Spring4 (only)

if you are NOT using Spring Boot, this can be overkill.

First, create a Condition class, in which the ConditionContext has access to the Environment:

public class MyCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context,
                           AnnotatedTypeMetadata metadata) {
        Environment env = context.getEnvironment();
        return null != env
                && "true".equals(env.getProperty("server.host"));
    }
}

Then annotate your bean:

@Bean
@Conditional(MyCondition.class)
public ObservationWebSocketClient observationWebSocketClient() {
    //return bean
}

2.Using Spring Boot:

@ConditionalOnProperty(name="server.host", havingValue="localhost")

And in your abcd.properties file ,

server.host=localhost

Upvotes: 61

Koos Gadellaa
Koos Gadellaa

Reputation: 1254

I have a snippet for such a thing. It checks the value of a property which is set in the annotation, so you can use things like

@ConditionalOnProperty(value="usenew", on=false, propertiesBeanName="myprops")
@Service("service")
public class oldService implements ServiceFunction{
    // some old implementation of the service function.
}

It even allows you to define different beans with the same name:

@ConditionalOnProperty(value="usenew", on=true, propertiesBeanName="myprops")
@Service("service")
public class newService implements ServiceFunction{
    // some new implementation of the service function.
}

These two can be declared at the same time, allowing you to have a "service" named bean with differing implementations depending on whether the property is on or off...

The snippet for it itself:

/**
 * Components annotated with ConditionalOnProperty will be registered in the spring context depending on the value of a
 * property defined in the propertiesBeanName properties Bean.
 */

@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Conditional(OnPropertyCondition.class)
public @interface ConditionalOnProperty {
    /**
     * The name of the property. If not found, it will evaluate to false.
     */
    String value();
    /**
     * if the properties value should be true (default) or false
     */
    boolean on() default true;
    /**
     * Name of the bean containing the properties.
     */
    String propertiesBeanName();
}

/**
 * Condition that matches on the value of a property.
 *
 * @see ConditionalOnProperty
 */
class OnPropertyCondition implements ConfigurationCondition {
    private static final Logger LOG = LoggerFactory.getLogger(OnPropertyCondition.class);

    @Override
    public boolean matches(final ConditionContext context, final AnnotatedTypeMetadata metadata) {
        final Map attributes = metadata.getAnnotationAttributes(ConditionalOnProperty.class.getName());
        final String propertyName = (String) attributes.get("value");
        final String propertiesBeanName = (String) attributes.get("propertiesBeanName");
        final boolean propertyDesiredValue = (boolean) attributes.get("on");

        // for some reason, we cannot use the environment here, hence we get the actual properties bean instead.
        Properties props = context.getBeanFactory().getBean(propertiesBeanName, Properties.class);
        final boolean propValue = parseBoolean(props.getProperty(propertyName, Boolean.toString(false)));
        LOG.info("Property '{}' resolved to {}, desired: {}", new Object[] { propertyName, propValue, "" + propertyDesiredValue });
        return propValue == propertyDesiredValue;
    }
    /**
     * Set the registration to REGISTER, else it is handled during  the parsing of the configuration file
     * and we have no guarantee that the properties bean is loaded/exposed yet
     */
    @Override
    public ConfigurationPhase getConfigurationPhase() {
        return ConfigurationPhase.REGISTER_BEAN;
    }
}

Upvotes: 9

Related Questions