【问题标题】:Externalize @InitBinder initialization into WebBindingInitializer将 @InitBinder 初始化外部化到 WebBindingInitializer
【发布时间】:2016-01-11 04:20:26
【问题描述】:

数据绑定初始化有两种主要的方法,但是老派的有一个缺点,我想不通。这种注释方式很棒:

@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 中创建的,并且初始化程序会在 HandlerMethodInvoker 中的某处传递活页夹实例,所以我无法设置它......我不能做这样的事情:

<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>

因为 binder 实例是在 handlerAdapter 中传入的。那我该如何设置活页夹呢?

【问题讨论】:

    标签: spring-mvc databinder


    【解决方案1】:

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

    或者你可以投票SPR-8601

    【讨论】:

      【解决方案2】:

      这已经很老了,但是对于那些不喜欢在生产代码中使用注释的人(比如我)来说,这是我发现的一个解决方案,可以在不使用注释的情况下添加一个 init binder。您只需要覆盖从 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 方法也被覆盖。

      希望对你有帮助!!!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-06-15
        • 1970-01-01
        • 1970-01-01
        • 2018-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多