Spring Test中的 @ActiveProfiles不再支持占位符



我正在从Spring 4.3升级到Spring 5.3,似乎@ActiveProviles注释不再支持占位符。

下面的代码可以在旧的Spring版本中使用:

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles({"${profileA}","someProfileWithoutPlaceholders"})
@ContextConfiguration(classes = MyApplication.class)
public class MyTest {...}

但是它在升级时停止工作,现在它得到

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'nucleus.hibernate.dialect' in value "${nucleus.hibernate.dialect}"
at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:178)
at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:124)
at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:239)
at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:210)
at org.springframework.context.support.PropertySourcesPlaceholderConfigurer.lambda$processProperties$0(PropertySourcesPlaceholderConfigurer.java:175)
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveEmbeddedValue(AbstractBeanFactory.java:936)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1321)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1300)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:119)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399)
... 55 more

注意,'nucleus.hibernate。${profileA}"引用的应用程序属性中定义了"dialect"。

作为解决方案,我尝试使用

显式地指定属性作为测试属性源。
@TestPropertySource(locations={"classpath:/application-${profileA}.properties"}})

,这是有效的

我不确定在Spring集成测试中使用占位符来选择Spring配置文件是否是官方支持的特性。如果是,我认为这是Spring测试框架中的一个突破性的变化。

在调试了测试用例之后,我对这个问题有了更多的了解。

似乎在

org.springframework.core.env.PropertySourcesPropertyResolver#getProperty(java.lang.String, java.lang.Class<T>, boolean)

测试属性源'test'分割了概要文件,并且有两个条目:

spring.profiles.active[0] -> "${profileA}
spring.profiles.active[1] -> "someProfileWithoutPlaceholders"

所以当用键"spring.profiles.active"查找时,它找不到任何值,并且没有调用org.springframework.core.env.AbstractPropertyResolver#resolveNestedPlaceholders

这是在org.springframework.core.env.AbstractEnvironment#doGetActiveProfiles构建测试应用程序上下文时完成的。

在旧的Spring版本中,只有一个map条目:

spring.profiles.active -> "${profileA},someProfileWithoutPlaceholders"

所以它找到了条目并解析了占位符

最新更新