0

I have a Spring boot application where I am reading a JSON property file with @ConfigurationProperties annotation:

@Component
@ConfigurationProperties(prefix = "my-config")
@RefreshScope
public class MyConfig {

    private List<Service> services;

    private List<Consumer> consumers;

    ...

Here I would like to add validation while Spring Boot load the property file if something is null or minimum value in the array/list is 1 etc..

I know Spring Boot is using Jackson in the background to perform marshall/unmarshalling between JSON and POJO. I cannot find anything in Jackson which enforce this validation.

Different forums suggest the standard JSR-303 validation however it only works with Rest APIs and not while loading the properties.

adesai
  • 370
  • 3
  • 22
  • Take a look at [@Valid when creating objects with jackson without controller](https://stackoverflow.com/questions/55457754/valid-when-creating-objects-with-jackson-without-controller) question. There is an example how to enable validation during deserialisation process. You just need to register deserialiser in `Spring` `ObjectMapper` instance which is used for deserialisation. – Michał Ziober Sep 19 '19 at 18:47

1 Answers1

1

you can validate your properties with JSR-303 annotations like that:

@Validated
@Component
@ConfigurationProperties(prefix = "my-config")
@RefreshScope
public class MyConfig {

    @NotNull
    @NotEmpty
    @Size(min = 1, max = 5)
    private List<Service> services;

    private List<Consumer> consumers;
...

and so on.

@Validated enable validation every time annotated field get a value

Luke
  • 516
  • 2
  • 10