将@InitBinder初始化外部化为WebBindingInitializer

时间:2011-08-10 16:19:34

标签: spring-mvc databinder

有两种主要的数据绑定初始化方法,但是在oldschool中有一个缺点,我无法弄清楚。这种注释方式很棒:

@InitBinder("order")
public void initBinder(WebDataBinder binder) {
    // Problem is that I want to set allowed and restricted fields - can be done here
    binder.setAllowedFields(allowedFields.split(","));
}

但我无法使用ConfigurableWebBindingInitializer完成。首先,在AnnotationMethodHandlerAdapter中创建binder实例,初始化器在HandlerMethodInvoker中的某个地方传递binder实例,所以我无法设置它...我不能做这样的事情:

<bean id="codesResolver" class="org.springframework.validation.DefaultMessageCodesResolver" />
<bean id="binder" class="org.springframework.web.portlet.bind.PortletRequestDataBinder" scope="prototype">
    <property name="allowedFields" value="${allowedFields}" />
    <aop:scoped-proxy />
</bean>
<bean id="webBindingInitializer" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
    <property name="messageCodesResolver" ref="codesResolver" />
</bean>

因为在handlerAdapter中将binder实例传递给它。我怎样才能设置活页夹呢?

2 个答案:

答案 0 :(得分:2)

无法在xml配置中进行设置。您必须实现自定义WebBindingInitializer ... ConfigurableWebBindingInitializer显然缺少设置允许和受限字段的可能性......

或者您可以投票SPR-8601

答案 1 :(得分:0)

这是非常古老的,但对于那些不喜欢在生产代码中使用注释的人(像我一样),这里是一个解决方案,我发现在不使用注释的情况下添加init绑定器。您只需要覆盖从Spring提供的大多数基本控制器扩展的initBinder方法:

protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception
{
    System.out.println("Binding!!!!!");
    super.initBinder(request, binder);
    binder.registerCustomEditor(Double.class, new CurrencyPropertyEditor());
}

我的CurrencyPropertyEditor类是java.beans.PropertyEditorSupport的子类,其中getAsText,getValue,setValue和setAsText方法也被覆盖。

希望它有所帮助!!!

相关问题