根据 属性 on Spring Boot 实例化一个服务

Instantiate a service according to a property on Spring Boot

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

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

我没有使用配置文件。

P.S。当我说 属性 时,我的意思是 application.properties

中的 属性

看:

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
}

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