spring如何根据profile调用bean的不同实现

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


例如


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,但我得到一个异常,即缺少 Test 的 bean。


拉丁的传说
浏览 193回答 2
2回答

阿晨1998

添加默认配置文件Service2:@Service@Profile("default")class Service2 implements Test{    public void test(){    }}只有在没有识别出其他配置文件时,才会将 bean 添加到上下文中。如果您传入不同的配置文件,例如 -Dspring.profiles.active="demo",则忽略此配置文件。如果您想要除本地使用NOT 运算符之外的所有配置文件:@Profile("!local")如果给定配置文件以 NOT 运算符 (!) 为前缀,则在配置文件未激活时将注册带注释的组件

富国沪深

您可以添加@ConditionalOnMissingBean到 Service2 这意味着它将仅在不存在其他实现的情况下使用,这将有效地使 Service2 成为除本地以外的任何其他配置文件中的默认实现@Service@ConditionalOnMissingBeanclass Service2 implements Test {    public void test() {}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java