Spring-boot framework allows us to provide YAML files as a replacement for the .properties file and it is convenient.The keys in property files can be provided in YAML format in application.yml file in the resource folder and spring-boot will automatically take it up.Keep in mind that the yaml format has to keep the spaces correct for the value to be read correctly.
You can use the @Value("${property}")
to inject the values from the YAML files.
Also Spring.active.profiles can be given to differentiate between different YAML for different environments for convenient deployment.
For testing purposes, the test YAML file can be named like application-test.yml and placed in the resource folder of the test directory.
If you are specifying the application-test.yml
and provide the spring test profile in the .yml, then you can use the @ActiveProfiles('test')
annotation to direct spring to take the configurations from the application-test.yml that you have specified.
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ApplicationTest.class)
@ActiveProfiles("test")
public class MyTest {
...
}
If you are using JUnit 5 then no need for other annotations as @SpringBootTest already include the springrunner annotation. Keeping a separate main ApplicationTest.class enables us to provide separate configuration classes for tests and we can prevent the default configuration beans from loading by excluding them from a component scan in the test main class. You can also provide the profile to be loaded there.
@SpringBootApplication(exclude=SecurityAutoConfiguration.class)
public class ApplicationTest {
public static void main(String[] args) {
SpringApplication.run(ApplicationTest.class, args);
}
}
Here is the link for Spring documentation regarding the use of YAML instead of .properties
file(s): https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html