snowery
snowery

Reputation: 468

spring boot application context was not properly loaded if the yaml file wasn't application.yml

With following configuration, my test can read the properties from the yaml file correctly.

@SpringBootApplication
@PropertySource("classpath:application.yml")
@ComponentScan({ "com.my.service" })
public class MyApplication {

}

Then I renamed the yaml file to my-application.yml, and changed the PropertySource to

@PropertySource("classpath:my-application.yml")

Tests are failed due to the null property value. The configuration class is as following:

@Configuration
@ConfigurationProperties(prefix="my")
@Data
public class MyConfig {
    private String attr1;
}

The test class is:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MyApplication.class)
public class MyConfigTest {

@Autowired
private MyConfig myConfig;

@Test
public void getMyConfigTest() {
    Assert.assertNotNull(myConfig.getAttr1());
}

Why spring boot can find the renamed yaml file, but it couldn't load the value correctly?

Upvotes: 0

Views: 1316

Answers (1)

Dave Bower
Dave Bower

Reputation: 3557

YAML files can’t be loaded via the @PropertySource annotation

It appears to work with @PropertySource("classpath:application.yml") because that's the default location and spring boot looks there regardless.

You may be able to use @ConfigurationProperties(location="claspath:my-application.yml") instead but it doesn't really achieve the same purpose (and I've never tried it myself).

Upvotes: 2

Related Questions