Spring @PropertySource 使用 YAML [英] Spring @PropertySource using YAML
问题描述
Spring Boot 允许我们用 YAML 等效文件替换我们的 application.properties
文件.但是,我的测试似乎遇到了障碍.如果我注释我的 TestConfiguration
(一个简单的 Java 配置),它需要一个属性文件.
Spring Boot allows us to replace our application.properties
files with YAML equivalents. However, I seem to hit a snag with my tests. If I annotate my TestConfiguration
(a simple Java config), it is expecting a properties file.
例如这不起作用:@PropertySource(value = "classpath:application-test.yml")
如果我的 YAML 文件中有这个:
If I have this in my YAML file:
db:
url: jdbc:oracle:thin:@pathToMyDb
username: someUser
password: fakePassword
我会用这样的方式来利用这些价值:
And I'd be leveraging those values with something like this:
@Value("${db.username}") String username
但是,我最终遇到了这样的错误:
However, I end up with an error like so:
Could not resolve placeholder 'db.username' in string value "${db.username}"
我怎样才能在我的测试中利用 YAML 的优点?
How can I leverage the YAML goodness in my tests as well?
推荐答案
Spring-boot 有一个帮手,只需添加
Spring-boot has a helper for this, just add
@ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class)
在您的测试类或抽象测试超类的顶部.
at the top of your test classes or an abstract test superclass.
我五年前写了这个答案.它不适用于最新版本的 Spring Boot.这就是我现在所做的(如有必要,请将 Kotlin 翻译成 Java):
I wrote this answer five years ago. It doesn't work with recent versions of Spring Boot. This is what I do now (please translate the Kotlin to Java if necessary):
@TestPropertySource(locations=["classpath:application.yml"])
@ContextConfiguration(
initializers=[ConfigFileApplicationContextInitializer::class]
)
被添加到顶部,然后
@Configuration
open class TestConfig {
@Bean
open fun propertiesResolver(): PropertySourcesPlaceholderConfigurer {
return PropertySourcesPlaceholderConfigurer()
}
}
上下文.
这篇关于Spring @PropertySource 使用 YAML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!