irfan bhindawala
irfan bhindawala

Reputation: 23

How to load a bean only if the property value is other than a fixed value

I am facing a situation in which a bean should be created by the application context only if the property contains any other value than a specific value. i.e... one property file.path= /specific/path, If the value is other than this then bean should be loaded.

I can see that there is @ConditionalOnProperty (name="file.path", havingValue="....") out of the box but in my case, I am looking a property like havingValueOtherThan="..." or similar kind of property or annotation if it is there out of the box in the spring.

Upvotes: 0

Views: 776

Answers (1)

Mark Bramnik
Mark Bramnik

Reputation: 42541

There are many possible options, besides profiles that were stated in comments, here are 2 options:

Option 1

Use @ConditionalOnExpression with any SPeL expression you wish

Option 2

You can always create your own conditional annotation with any logic:

Create an annotation that will depict your own business case with a @Conditional on it. Then Implement the conditional logic of your choice. Here is an example of achieving this.

BTW, the profiles that mentioned in comments are using Conditionals engine under the hood (The @Profile annotation has a @Conditional({ProfileCondition.class}) in its definition since Spring 4.x)

Upvotes: 5

Related Questions