Search code examples
spring-bootconfigurationproperties

Fail during startup if unknown properties are defined?


I am using spring boot configuration properties with an optional property:

@ConfigurationProperties("my.properties")
public class MyProperties {

    List<String> optional = new ArrayList(); // optional property

    // getters/setters
}

I want my application to fail during startup when there is a property defined in my application.yml which is NOT defined in my properties class, since this might be caused by a typo and therefore to prevent mistakes when configuring applications. e.g:

my:
  properties:
    optional2:
      - foo
      - bar

Is this possible, for example by setting a flag?


Solution

  • You can set ignoreUnknownFields to false on the @ConfigurationProperties annotation (@ConfigurationProperties(value = "foo", ignoreUnknownFields = false)).

    If you would, an exception would be thrown when there is no corresponding field on the java class for a property (like the optional2 propery in your example).

    See: https://tedblob.com/configurationproperties-ignoreunknownfields/

    The @ConfigurationProperties provide an optional element ignoreUnknownFields using which you can ignore or throw errors for the unknown fields during binding the properties.