【问题标题】:WebBindingInitializer won't executeWebBindingInitializer 不会执行
【发布时间】:2013-09-28 21:58:56
【问题描述】:

如何让initBinder() 方法在每次表单加载和提交时启动。此示例负责将日期从 String 转换为 java.util.Date

在我的 servlet-context.xml 中:

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

这是我的 WebBindingInitializer 实现:

public class ExampleBindingInitializer implements WebBindingInitializer {

    private ExampleService exampleService;

    @Autowired
    public ExampleBindingInitializer(ReservationService reservationService) {
        this.reservationService = reservationService;
    }

    public void initBinder(WebDataBinder binder, WebRequest request) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
}

我没有在调用 ExampleService 方法的控制器中进行任何修改。我哪里错了?

当我将带有@InitBinder 注释的initBinder() 方法放入我的控制器时,一切正常。这不满足我,因为我想在外部课程中拥有它。

【问题讨论】:

  • 你能发布接受包含日期的对象的控制器方法吗?
  • 实际上是否有效取决于您使用的 Spring 版本。请添加版本。如果您使用的是较新的 spring 版本,则应使用 RequestMappingHandlerAdapter 而不是 AnnotationMethodHandlerAdapter

标签: java spring spring-mvc


【解决方案1】:

确保您的配置中包含&lt;mvc:annotation-driven/&gt;,并且在它之前声明了您的bean。

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

<mvc:annotation-driven/>

当 Spring 扫描处理程序时,将使用第一个注册的匹配处理程序。 mvc:annotation-driven 注册了一些处理程序,这些处理程序可能被用来代替您的处理程序。

【讨论】:

  • 没有成功。在配置的开始,我把这个。之后,我有静态资源的 mvc:resources 标签、切片配置、我的包上的组件扫描、特定异常的 SimpleMappingExceptionResolver 和最后的 ResourceBundleMessageSource。
【解决方案2】:

您必须从 dispatcher-servlet 中删除或注释掉 &lt;mvc:annotation-driven/&gt;Documentation

【讨论】:

    【解决方案3】:

    您使用的类 AnnotationMethodHandlerAdapter 已过时且已弃用。你不应该使用它。

    我假设您有&lt;mvc:annotation-driven /&gt;@EnableWebMvc,它们注册了推荐和支持的RequestMappingHandlerAdapter。您可以创建一个BeanPostProcessor 来在RequestMappingHandlerAdapter 上设置所需的属性。

    但是,您实际上应该做的是创建一个自定义转换器并使用 &lt;mvc:annotation-driven /&gt; 命名空间进行注册。这是推荐的做事方式,不再使用WebBindingInitializer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-10
      • 2017-11-21
      • 2015-11-10
      相关资源
      最近更新 更多