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.

spring:
  profiles: local
  application:
    name: SERVICE

server:
  port: 8090
  ssl:
    enabled: false

mocking:
  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.

@Service
public class AddressService {

    @Value("${mocking.enabled")
    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.

@ExtendWith(SpringExtension.class)
class AddressServiceTest {

    @InjectMocks
    AddressService addressService;

    @Test
    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. Required fields are marked *