How to read and override Spring Boot YAML Properties

There are some cases where we need to read and override YAML properties for implementation and testing purposes. This short tutorial will teach you how to do it. You can find the source code on GitHub.

Project Structure

The project structure is as follows.

Reading a YAML Property

There are some cases that we read YAML properties during runtime. Let’s create an application.yml file is under src/main/resource.

  profiles: local
    name: SERVICE

  port: 8090
    enabled: false

  enabled: false
  postcodes: NE43YV,QA12ED,DF53TH

@Value annotation reads property in a Java class. You just need to create a class variable. Here is an example that reads mocking.enabled property to fetch address details.

public class AddressService {

    private String isMocked;

    public AddressResponse getAddressDetails(final long id) {
        if (Boolean.parseBoolean(isMocked)) {
            return getStubbedAddresses(id);
        } else {
            return getAddressesFromRestApi(id);

Overriding a YAML Property

Sometimes we need to use different values than we defined in the YAML file for testing purposes. In this case, we can override the YAML using ReflectionTestUtils.setField method. In this example, we want to test the mocked addresses. Therefore, we set the value to true.

class AddressServiceTest {

    AddressService addressService;

    void testMockedGetAddressDetails() {
        ReflectionTestUtils.setField(addressService, "isMocked", String.valueOf(true));
        AddressResponse expectedResult = new AddressResponse(19, "stubbed road", "Newcastle", "NE45WS");
        AddressResponse actualResult = addressService.getAddressDetails(1L);
        assertEquals(expectedResult, actualResult);

Leave a Reply

Your email address will not be published.