我有嵌套的属性类:
@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");
}
}
}
}
现在,我希望对两个类都触发验证,但是当我使用无效值运行时,仅对MyAppProperties触发验证,而对服务器列表不触发。
我做错了什么,我无法完成这项工作。我想同时使用自定义验证器。谁能帮我做这个工作。
我传递的无效值是:
myapp.servers[0].name=
myapp.servers[0].url=
但这可以正常运行