Hayk  Mkhitaryan
Hayk Mkhitaryan

Reputation: 468

@ConditionalOnProperty on a Bean, which must be loaded based on two conditions, coming from application.yml config file

I'm facing this kind of issue now, that I must give two conditions in one @ConditionalOnProperty which is class level.

I have a bean, say

@RestController
@RequestMapping("/blablabla")
@ConditionalOnProperty(prefix = "my.property.value1", name = "enabled", havingValue = "true")
public class MyBean{}

now there is a requirement that MyBean must be loaded based on two conditions, one is my.property.value1.enabled:true and the second is my.property.value2:true (both coming from application.yml file)

Now my question is there any way of doing this in one @ConditionalOnProperty annotation, if yes, so please paste here the working example. Thanks in advance.

Upvotes: 1

Views: 5785

Answers (3)

lkatiforis
lkatiforis

Reputation: 6255

For simple boolean properties you could use @ConditionalOnProperty:

@ConditionalOnProperty({"my.property.value1", "my.property.value2"})

application.yml:

my:
  property:
    value1: true
    value2: false

Upvotes: 2

M A
M A

Reputation: 72844

The @ConditionalProperty name element can support an array:

@ConditionalOnProperty(prefix = "my.property", name = {"value1.enabled", "value2.enabled"}, havingValue = "true")

If the two properties are compared to different values, then you can leverage a Spring expression:

@ConditionalOnExpression("${my.property.value1.enabled} == true and ${my.property.value1.enabled} == true")

Upvotes: 1

João Dias
João Dias

Reputation: 17460

Yes, you can do the following:

@ConditionalOnExpression("${my.property.value1.enabled} and ${my.property.value2}")

Upvotes: 1

Related Questions