Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot - @ConditionalOnProperty or @ConditionalOnExpression

Tags:

I'm using Spring-Boot-1.1.7. My intention is to add a bean to my context according to a value of a property of type string.

I mean, I can see a lot of examples of boolean values such as this:

@ConditionalOnExpression("${xxx.enabled:true}") 

But I want an expression based on a value of a property, for example:

@ConditionalOnExpression("${server.host==localhost} or ${server.port==8080} ") 

or something like that.

Can someone show me an example how to do it?

like image 660
Modi Avatar asked Oct 19 '14 14:10

Modi


People also ask

What is @ConditionalOnProperty in spring boot?

The Spring framework provides the @ConditionalOnProperty annotation precisely for this purpose. In short, the @ConditionalOnProperty enables bean registration only if an environment property is present and has a specific value. By default, the specified property must be defined and not equal to false.

What are conditional beans in spring boot?

Why do we need Conditional Beans? A Spring application context contains an object graph that makes up all the beans that our application needs at runtime. Spring's @Conditional annotation allows us to define conditions under which a certain bean is included into that object graph.

What is the use of @ConditionalOnExpression?

The @ConditionalOnExpression annotation lets configuration be included based on the result of a SpEL (Spring Expression Language) expression. For this example the Module class is only loaded if a particular SpEL is enabled.

How do I remove Spring beans based on specific conditions?

In Spring Boot, you can use the @ConditionalOnProperty annotation to enable or disable a particular bean based on the presence of a property. This is very useful if you want to provide optional features to your microservice. And that's it. Your optionalClass bean should resolve to null when you specify mybean.


2 Answers

Eventually , this one worked for me:

@ConditionalOnExpression("'${server.host}'=='localhost'") 
like image 162
Modi Avatar answered Dec 20 '22 04:12

Modi


For property value conditional I used:

@ConditionalOnProperty(name="server.host", havingValue="localhost") 
like image 38
davorp Avatar answered Dec 20 '22 04:12

davorp