开发者社区> 问答> 正文

webBindingInitializer 在XML中无效

public class CustomBindingInitializer implements WebBindingInitializer {

    @Override
    public void initBinder(WebDataBinder binder, WebRequest request) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                dateFormat.setLenient(false);
                binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }

}

xml中配置如下:

<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
            </list>
        </property>
        <property name="webBindingInitializer">
            <bean class="com.demo.util.CustomBindingInitializer"/>
        </property>
    </bean>

发现webBindingInitializer不起作用

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
            </list>
        </property>
        <property name="webBindingInitializer">
            <bean class="com.demo.util.CustomBindingInitializer"/>
        </property>
    </bean>
<mvc:annotation-driven/>

网上找到把放到下面就可以了,不过没有解释,有人知道是为什么吗

展开
收起
a123456678 2016-03-16 11:09:15 2478 0
1 条回答
写回答
取消 提交回答
  • 使用conversion-service来注册自定义的converter DataBinder实现了PropertyEditorRegistry, TypeConverter这两个interface,而在spring mvc实际处理时,返回值都是return binder.convertIfNecessary(见HandlerMethodInvoker中的具体处理逻辑)。因此可以使用customer conversionService来实现自定义的类型转换。 从中配置可以看出,AnnotationMethodHandlerAdapter已经配置了webBindingInitializer,我们可以通过设置其属性conversionService来实现自定义类型转换。 需要修改spring service context xml配置文件中的annotation-driven,增加属性conversion-service指向新增的conversionService bean。 实际自定义的converter如下。 public class DateConverter implements Converter { @Override public Date convert(String source) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); dateFormat.setLenient(false); try { return dateFormat.parse(source); } catch (ParseException e) { e.printStackTrace(); } return null; }

    2019-07-17 19:03:39
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关课程

更多

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载