1

I have nested properties class:

@ConfigurationProperties(prefix = "myapp", ignoreUnknownFields = false)
public class MyAppProperties implements Validator {

    @Valid
    private List<Server> servers = new ArrayList();

    public MyAppProperties() {
    }

    public List<Server> getServers() {
        return this.servers;
    }

    public void setServers(List<Server> servers) {
        this.servers = servers;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return MyAppProperties.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        MyAppProperties properties = (MyAppProperties) target;

        if (isEmpty(properties.getServers())) {
            errors.rejectValue("servers", "myapp.servers", "Servers not provided");
        }
    }

    public static class Server implements Validator {

        private String name;
        private String url;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        @Override
        public boolean supports(Class<?> clazz) {
            return Server.class.isAssignableFrom(clazz);
        }

        @Override
        public void validate(Object target, Errors errors) {
            Server server = (Server) target;

            if (StringUtils.isBlank(server.getName())) {
                errors.rejectValue("name", "server.name", "Server name not provided");
            }

            if (StringUtils.isBlank(server.getUrl())) {
                errors.rejectValue("url", "server.url", "Server url not provided");
            }
        }
    }
}

Now i want the validation to fire for both classes, but when i run with invalid values, the validation fires only for MyAppProperties but not for the list of Servers.

Am i doing something wrong, i'm not able to make this work. I want to use custom validator for both. Can anybody please help me make this work.

The invalid values that i pass are:

myapp.servers[0].name= 
myapp.servers[0].url=

But this runs without any error

Kiba
  • 399
  • 1
  • 4
  • 16
  • have you seen this answer? -> https://stackoverflow.com/a/23419120/2568469 – hatef Dec 16 '18 at 12:18
  • 1
    @Hatef StringUtils is of Spring, it checks for both null and empty string. I also tested the same with commons-lang3 StringUtils.isBlank – Kiba Dec 16 '18 at 12:20
  • Ah okay! I'm not a Spring developer but maybe you can try to debug by printing what is actually being passed to that method :) – hatef Dec 16 '18 at 12:27
  • 1
    @Hatef Thank you for quick reply. I did that also but the validator of Server class is not being called – Kiba Dec 16 '18 at 12:29

0 Answers0