Spring Boot properties in 'application.yml'

2020-05-16 15:21发布

What am I doing wrong? I'm using this little standalone App which runs and finds my src/main/resources/config/application.yml. The same configuration doesn't work from JUnit, see below:

@Configuration
@ComponentScan
@EnableConfigurationProperties

public class TestApplication {

    public static void main(String[] args) {

        SpringApplication.run(TestApplication.class);
    }
}


@Component
@ConfigurationProperties

public class Bean{
    ...
}

The following doesn't work, the same properties in application.yml are not loaded and Bean has only null values:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestApplication.class)

public class SomeTestClass {
    ...
}

9条回答
戒情不戒烟
2楼-- · 2020-05-16 15:56

Spring boot 2 example:

private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
        .withInitializer(new ConfigFileApplicationContextInitializer());

@Test public void test() throws Exception {

    this.contextRunner
    .withUserConfiguration(TestApplication.class)
    .run((context) -> {

        .....

    });
}
查看更多
可以哭但决不认输i
3楼-- · 2020-05-16 16:01

adding to Liam's answer, an alternative will be:

@TestPropertySource(locations = { "classpath:application.yaml" })

the key difference here is that the test will fail with a file not found exception if application.yaml is not in your /test/resources directory

查看更多
Lonely孤独者°
4楼-- · 2020-05-16 16:02

In my case I was trying to test a library without a @SpringBootApp declared in the regular app classpath, but I do have one in my test context. After debugging my way through the Spring Boot initialization process, I discovered that Spring Boot's YamlPropertySourceLoader (as of 1.5.2.RELEASE) will not load YAML properties unless org.yaml.snakeyaml.Yaml is on the classpath. The solution for me was to add snakeyaml as a test dependency in my POM:

    <dependency>
        <groupId>org.yaml</groupId>
        <artifactId>snakeyaml</artifactId>
        <version>1.19</version>
        <scope>test</scope>
    </dependency>
查看更多
登录 后发表回答