自学内容网 自学内容网

接口报错500InvalidPropertyException: Invalid property ‘xxx[256]‘,@InitBinder的使用

org.springframework.beans.InvalidPropertyException: Invalid property ‘xxx[256]’ of bean class [com.xxl.MailHead]: Invalid list index in property path ‘xxx[256]’; nested exception is java.lang.IndexOutOfBoundsException: Index: 256, Size: 256

从报错可以看到,前端传入参数个数大于256个,后端使用List接参,超出数组大小限制。
有两种方式修改:

1.局部设置

在controller中增加以下代码,只对该controller生效

@InitBinder
public void initBinder(WebDataBinder binder) {
binder.setAutoGrowNestedPaths(true);
binder.setAutoGrowCollectionLimit(1024);
}

这个更改做了以下几点:
增加了@InitBinder注解的方法,这将应用于这个控制器中的所有请求处理方法。
setAutoGrowNestedPaths(true)允许嵌套路径自动增长,这对于复杂对象很有用。
setAutoGrowCollectionLimit(1024)将集合的自动增长限制设置为1024,这应该足以处理您之前遇到的256个参数的限制问题。

2.全局设置

通过实现WebBindingInitializer接口并在Spring MVC配置文件中注册,可以全局设置数据绑定器的属性。适用于需要在整个应用程序中进行统一配置的情况

public class DataBindingInitializer implements WebBindingInitializer{

@Override  
    public void initBinder(WebDataBinder binder, WebRequest request) {  
        binder.setAutoGrowCollectionLimit(100000);  
    }  
}

在xml中配置

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="webBindingInitializer">
<bean class="xxx.DataBindingInitializer"/>
</property>
</bean>

看到其他文章说:当使用了<mvc:annotation-driven />的时候,会自动注册DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter 两个bean。这时候第二种方式指定的全局属性编辑器就不会起作用了,解决办法就是手动的添加上述bean,并把它们加在mvc:annotation-driven/的前面。如果不生效,则将手动注册AnnotationMethodHandlerAdapter改为手动注册RequestMappingHandlerAdapter。

也有小伙伴说第二种方式最好不使用,覆盖掉框架WebBindingInitializer,导致校验框架失效等问题

总结还是第一种局部设置比较保险,就是每个controller都需要设置


原文地址:https://blog.csdn.net/qq_23888451/article/details/142495273

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!