Spring - 使用@ActiveProfiles覆盖spring.profiles.active属性

3

我的每个测试都附有注释

@TestPropertySource(locations = "classpath:application-test.properties")
application-test.properties的内容以spring.profiles.active=..开头。如果将其设置为testdev,则会通过匹配在application-testdev.properties中找到的属性覆盖这些属性。类似地,如果设置为testuat,则会使用application-testuat.properties进行覆盖。

然而,如果没有设置testuat,则某些测试实际上是没有意义的,因此我还用@ActiveProfiles("testuat")对它们进行了注释。当我在application-test.properties中设置spring.profiles.active=testdev运行时,它似乎忽略了testuat属性,只读取了基本属性和testdev属性。

有没有一种方法可以使用@ActiveProfiles覆盖spring.active.profiles

感谢您的帮助。


你是否需要手动更改 spring.profiles.active= 来在每个环境中运行测试? - undefined
是的,我目前正在手动设置那个。 - undefined
也许你可以使用SPRING_PROFILES_ACTIVE环境变量来替代在文件中设置它。然后在你的测试中设置它,并创建必要的属性文件。 - undefined
1个回答

2
默认情况下,@ActiveProfiles 优先于 spring.actives.profiles 设置,但您可以使用更灵活的行为实现自己的 ActiveProfilesResolver。以下是一个示例实现,默认为 test ,如果将其设置为系统属性,则可以选择添加第二个配置文件。
请使用以下代码替换@ActiveProfiles("testuat")@ActiveProfiles(resolver = SpringActiveProfilesResolver.class) 并在测试代码库中的任何位置添加此类:
public class SpringActiveProfilesResolver implements ActiveProfilesResolver {
    @Override
    public String[] resolve(Class<?> aClass) {
        List<String> springProfiles = Lists.newArrayList("test");
        String systemSpringProfile = System.getProperty("spring.profiles.active");
        if(StringUtils.isNotBlank(systemSpringProfile)) {
            springProfiles.add(systemSpringProfile);
        }
        return springProfiles.toArray(String[]::new);
    }
}

我希望能够在开箱即用的情况下看到@IncludeProfiles注解。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接