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.
To conditionally create a bean, we must first create an implementation of Condition. The Condition interface contains the matches method which returns a boolean value. Here, the AuditEnabledCondition class is checking whether audit. enabled is true using the Environment properties.
Conditions based on a Bean definition are present in Spring Application context. Conditions based on a Bean object are present in Spring Application context. Conditions based on some or all Bean properties values. Conditions based on some Resources are present in current Spring Application Context or not.
There are three different ways in which you can define a Spring bean: annotating your class with the stereotype @Component annotation (or its derivatives) writing a bean factory method annotated with the @Bean annotation in a custom Java configuration class. declaring a bean definition in an XML configuration file.
To declare a bean, simply annotate a method with the @Bean annotation. When JavaConfig encounters such a method, it will execute that method and register the return value as a bean within a BeanFactory .
You can use @Conditional from Spring4 or @ConditionalOnProperty from Spring Boot.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With