java未能在Spring、Spock和Groovy的测试中注入@Value
在使用Spring Boot&;在Spock中进行测试期间,我在bean中注入@Value('${mybean.secret}')
属性时遇到问题;棒极了
我有一个非常简单的测试类MyBeanTest
@ContextConfiguration(classes = [
MyAppConfig
])
@PropertySource([
"classpath:context/default-properties.yml"
])
class MyBeanTest extends Specification {
@Autowired
MyBean myBean
def "should populate properties "() {
expect:
myBean.secretProperty == "iCantTellYou"
}
}
和{
@Configuration
class MyAppConfig {
@Bean
MyBean credential(@Value('${mybean.secret}') String secret) {
return new MyBean(secret)
}
}
当我运行测试时,注入secret
的value
就是${mybean.secret}
。
实际值不是从properties
文件中注入的我随附在测试规范中
因为Groovy,我在@Value
上使用单引号。带有$
符号的双quote
使其由groovy GString机制处理
但是,这个问题在常规应用程序运行时不会发生
如果我启动应用程序并将断点放在MyAppConfig#credential
方法上,则secret
值将从属性文件中正确读取,其配置如下:
@Configuration
@PropertySource(["classpath:context/default-properties.yml"])
class PropertiesConfig {
}
当我像这样从手上指定属性时:
@TestPropertySource(properties = [
"mybean.secret=xyz"
])
class MyBeanTest extends Specification {
它起作用了。属性被读取。但这不是我的目标,因为项目中有更多的属性,从手边到处定义它们会变得很麻烦
你能找出我在代码中遗漏的问题吗
# 1 楼答案
缺失的谜题是YamlPropertySourceFactory
我使用了
yml
属性文件和嵌套属性:Spring没有正确加载它们
我必须更新
@PropertySource
注释,并执行以下操作:现在它就像一个符咒😏.
我在贝尔东网站上了解到这一点https://www.baeldung.com/spring-yaml-propertysource