Spring添加Show类校验器后访问/shows报Invalid target for Validator错误
报错本质是@InitBinder的作用域配置错误。
你在ShowController中定义的initBinder方法没有指定绑定的目标模型属性名,意味着这个方法中注册的ShowValidator,会被应用到当前Controller处理请求时所有WebDataBinder的参数绑定流程上——不管绑定的目标对象是Show、Channel还是其他类型。
你的ShowValidator本身仅支持校验Show类型对象(通过supports方法限定仅匹配Show类),当请求进入/shows路径时,Spring在为model中存放的Channel对象初始化对应的WebDataBinder时,会携带提前全局注册的ShowValidator执行校验前的类型检查,发现绑定目标是Channel类型而非Show类型,直接抛出IllegalStateException: Invalid target for Validator异常。
修复方案1:给@InitBinder限定作用域
只让当前binder中注册的ShowValidator,在处理名为"show"的模型属性时生效,不影响其他类型的参数绑定。
将原有initBinder代码修改为:
@InitBinder("show") // 仅对属性名为show的模型对象应用此binder的规则 protected void initBinder(WebDataBinder binder) { binder.addValidators(new ShowValidator()); }
修改后,访问/shows接口时,Spring处理Channel对象的绑定流程不会加载这个校验器,不会触发类型不匹配的错误;只有处理"show"属性(也就是addShow接口的Show入参)时,才会应用ShowValidator执行校验。
修复方案2:利用Spring自动校验机制
如果不需要对binder做其他自定义配置,可以完全移除initBinder中的全局校验器注册逻辑,依靠Spring MVC的自动匹配能力完成校验:
- 删除
ShowController中的整个initBinder方法 - 为
ShowValidator添加@Component注解,交给Spring容器托管:@Component public class ShowValidator implements Validator { // 原有校验逻辑保持不变 } - 保持
addShow接口上的@Valid注解不变:Spring会自动扫描容器中所有实现了Validator接口的Bean,根据每个Validator的supports方法匹配对应类型的入参,自动触发校验流程,不会对Channel类型的对象应用ShowValidator的校验规则。
额外细节修正
当前addShow方法中,校验失败后的返回路径写的是/show/form,但你定义的表单页面路径是/shows/form,缺少了路径中的s,后续校验触发时会出现404错误,需要将返回值调整为return "/shows/form";。
内容的提问来源于stack exchange,提问作者Sam Wong

