有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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)
    }
}

当我运行测试时,注入secretvalue就是${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) 个答案

  1. # 1 楼答案

    缺失的谜题是YamlPropertySourceFactory

    public class YamlPropertySourceFactory implements PropertySourceFactory {
    
        @Override
        public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) 
          throws IOException {
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(encodedResource.getResource());
    
            Properties properties = factory.getObject();
    
            return new PropertiesPropertySource(encodedResource.getResource().getFilename(), properties);
        }
    }
    

    我使用了yml属性文件和嵌套属性:

    mybean:
      secret: xyz
    

    Spring没有正确加载它们

    我必须更新@PropertySource注释,并执行以下操作:

    @Configuration
    @PropertySource(
        value = ["classpath:context/default-properties.yml"],
      factory = YamlPropertySourceFactory.class
    )
    class PropertiesConfig {
    }
    

    现在它就像一个符咒😏.

    我在贝尔东网站上了解到这一点https://www.baeldung.com/spring-yaml-propertysource