如何根据 spring 中的配置文件调用 bean 的不同实现

How to call different implementations of a bean based on profile in spring

我需要添加一个接口的多个实现,其中一个应该根据配置文件选择。

例如

interface Test{
    public void test();
}

@Service
@Profile("local")
class Service1 implements Test{
    public void test(){

    }
}

@Service
class Service2 implements Test{
    public void test(){

    }
}


@SpringBootApplication
public class Application {

    private final Test test;

    public Application(final Test test) {
        this.test = test;
    }

    @PostConstruct
    public void setup() {
        test.test();
    }
}

我的意图是当我使用 -Dspring.profiles.active=local 时应该调用 Service1 否则应该调用 service2 但我得到一个异常 缺少用于测试的 bean。

Service2 添加 default 配置文件:

@Service
@Profile("default")
class Service2 implements Test{
    public void test(){

    }
}

the bean will only be added to the context if no other profile is identified. If you pass in a different profile, e.g. -Dspring.profiles.active="demo", this profile is ignored.

如果您想要除本地使用之外的所有配置文件 NOT operator:

@Profile("!local")

If a given profile is prefixed with the NOT operator (!), the annotated component will be registered if the profile is not active

您可以将 @ConditionalOnMissingBean 添加到 Service2,这意味着它将仅在不存在其他实现的情况下使用,这将有效地使 Service2 成为除 local

之外的任何其他配置文件中的默认实现
@Service
@ConditionalOnMissingBean
class Service2 implements Test {
    public void test() {}
}