【问题标题】:Instantiate a service according to a property on Spring Boot根据 Spring Boot 上的属性实例化服务
【发布时间】:2019-08-23 10:58:18
【问题描述】:

一个好的做法是将服务定义为接口及其在类上的实现。

假设我有 2 个实现相同接口的类,我想根据属性(而不是配置文件)区分它们。我的意思是,如果我有@Autowire private MyServiceInterface myService;,我想收到PotatoServiceImpl 的实例,如果我有myproperty=potatoTomatoServiceImpl 的实例,如果我有myproperty=tomato

我没有使用个人资料。

附:当我说属性时,我指的是application.properties中的属性

【问题讨论】:

    标签: spring-boot dependency-injection autowired


    【解决方案1】:

    看:

    public interface MyInterface {
    }
    
    @Component
    @ConditionalOnProperty(prefix = "myproperty" havingValue = "potato", matchIfMissing = false)
    public class MyPotatoImpl implements MyInterface {
    }
    
    @Component
    @ConditionalOnProperty(prefix = "myproperty" havingValue = "tomato", matchIfMissing = false)
    public class MyTomatoImpl implements Myinterface {
    }
    
    @Component
    public class Consumer {
        @Autowire
        private MyInterface tomatoOrPotato; //depending on property myproperty value
    }
    

    这对我来说是一个非常优雅的解决方案,可以实现弹簧风格的策略创建设计模式。 查看here 获取有关@ConditionalOnProperty 注释的文档。

    【讨论】:

    • 我工作过,我只想说,你必须使用name,而不是使用prefix
    • 是的,你是对的。当您有一个由多个点分隔的属性组成的属性时,例如mySection.coolProperty,您可以将prefix 属性指定为mySection,将name 指定为coolProperty
    猜你喜欢
    • 2018-01-04
    • 2018-12-29
    • 2017-12-12
    • 1970-01-01
    • 2019-02-01
    • 2022-01-14
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    相关资源
    最近更新 更多