Spring boot - @ConditionalOnProperty or @ConditionalOnExpression

前端 未结 4 1055
长情又很酷
长情又很酷 2021-02-05 07:17

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 boole

相关标签:
4条回答
  • 2021-02-05 07:23

    If the value you want to compare with is a literal, you need to quote it, and the placeholder would go round the property name (not the whole expression), e.g. ${server.host}=='localhost'

    0 讨论(0)
  • 2021-02-05 07:23

    If you are using e.g. a string value and want to check if a value is set, you can use a simple "check":

    @Component
    @ConditionalOnProperty(value = "foo.value")
    public class Foo {
        private String value;
        // getter/ setter and other stuff ...
    }
    

    If you add: foo.value: bar to your application.yml file the component will be found and added to the application context, but if you do not set a value the component will not be added.

    If you want to check if the component is found, you can use: debug: true in your application.yml.

    Foo matched:
    - @ConditionalOnProperty (foo.value) matched (OnPropertyCondition)
    

    vs

    Foo: Did not match:
    - @ConditionalOnProperty (foo.value) did not find property 'foo.value' (OnPropertyCondition)
    
    0 讨论(0)
  • 2021-02-05 07:36

    For property value conditional I used:

    @ConditionalOnProperty(name="server.host", havingValue="localhost")
    
    0 讨论(0)
  • 2021-02-05 07:46

    Eventually , this one worked for me:

    @ConditionalOnExpression("'${server.host}'=='localhost'")
    
    0 讨论(0)
提交回复
热议问题