Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we declare spring bean conditionally?

Tags:

java

spring

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.

like image 362
Dimitrios Efthymiou Avatar asked Oct 04 '16 16:10

Dimitrios Efthymiou


People also ask

How do you conditionally create a bean?

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.

How do you use a Spring conditional bean?

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.

How many ways we can declare bean in Spring?

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.

How do you declare a Spring bean?

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 .


1 Answers

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 
like image 76
Sundararaj Govindasamy Avatar answered Oct 08 '22 15:10

Sundararaj Govindasamy