Java 如何在Spring中为多个概要文件设置默认实现?

Java 如何在Spring中为多个概要文件设置默认实现?,java,spring,Java,Spring,例如,我有许多概要文件,dev、prod、test等等 interface A @Component class DefaultImpl implements A @Profile("test") @Component class TestImpl implements A 我只希望TestImpl用于概要文件测试,而DefaultImpl用于所有其他概要文件 更新: @Profiledefault不适用于我的原因: 我有两个测试配置文件,即test1和test2 我在概要文件test1中

例如,我有许多概要文件,dev、prod、test等等

interface A

@Component
class DefaultImpl implements A

@Profile("test")
@Component
class TestImpl implements A
我只希望TestImpl用于概要文件测试,而DefaultImpl用于所有其他概要文件

更新: @Profiledefault不适用于我的原因:

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

我在概要文件test1中提供了一个不同的实现:

@Profile("default")
class DefaultImpl extends A

@Profile("test1")
class Test1Impl extends A
现在,当我@ActivateProfiletest2时,它不会选择DefaultImpl

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

class DefaultImpl extends A

@Profile("test1")
class Test1Impl extends A
profile test2最终将有两个bean,并且不知道连接哪个bean

现在,只有这样才能起作用:

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

@Profile("test1")
class Test1Impl extends A
除了在DefaultImpl中添加所有其他配置文件名之外,我还能做什么吗?

在DefaultImpl上使用@Profiledefault

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

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

如果不指定配置文件,将获得默认配置文件

因此,在您的示例中,如果您不使用配置文件,将加载DefaultImpl。如果将配置文件设置为使用以下工具进行测试:

@ActiveProfiles("test") or -Dspring.profiles.active=test
您将获得bot DefaultImpl和TestImpl

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

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