【问题标题】:How to set default implementation for multiple profiles in Spring?如何在 Spring 中为多个配置文件设置默认实现?
【发布时间】:2017-01-18 09:58:16
【问题描述】:

例如,我有很多配置文件,“dev”、“prod”、“test”等。

interface A

@Component
class DefaultImpl implements A

@Profile("test")
@Component
class TestImpl implements A

我只希望 TestImpl 用于配置文件“test”,而 DefaultImpl 用于所有其他配置文件。

更新: 为什么@Profile("default") 对我不起作用:

我有两个测试配置文件,即“test1”和“test2”

我在配置文件“test1”中提供了不同的实现:

@Profile("default")
class DefaultImpl extends A

@Profile("test1")
class Test1Impl extends A

现在当我@ActivateProfile("test2") 时,它不会选择 DefaultImpl

但是,如果我不设置配置文件,如下所示:

class DefaultImpl extends A

@Profile("test1")
class Test1Impl extends A

profile "test2" 最终会有两个 bean 并且不知道要连接哪个。

目前,只有这个可行:

@Profile("test2", "prod", ....)
class DefaultImpl extends A

@Profile("test1")
class Test1Impl extends A

除了在 DefaultImpl 中添加所有其他配置文件名称之外,我还能做什么?

【问题讨论】:

    标签: java spring


    【解决方案1】:

    如果您不指定配置文件,您将获得“默认”配置文件。

    因此,在您的示例中,如果您不使用配置文件,则会加载 DefaultImpl。如果您将配置文件设置为测试:

    @ActiveProfiles("test") or -Dspring.profiles.active=test
    

    你会得到机器人 DefaultImpl 和 TestImpl

    您可以更改以确保 DefaultImpl 不会运行以进行测试:

    @Profile("default")
    @Component
    class DefaultImpl implements A
    

    【讨论】:

      【解决方案2】:

      在 DefaultImpl 上使用 @Profile("default")

      或者,您可以创建一个特定的命名默认值并在您的 web.xml 中指定它:

      <context-param>
          <param-name>spring.profiles.default</param-name>
          <param-value>mydefault<param-value>
      </context-param>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-10-08
        • 1970-01-01
        • 1970-01-01
        • 2016-03-21
        • 1970-01-01
        • 2020-06-01
        • 2021-02-01
        • 2012-05-30
        相关资源
        最近更新 更多