java - Spring 4 ControllerAdvice 和 InitBinder

标签 java spring spring-mvc-initbinders

我正在尝试使用 @ControllerAdvice 类中的 @InitBinder 注解方法来注册全局 InitBinder。

package com.myapp.spring.configuration;

import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@ControllerAdvice
@EnableWebMvc
public class CustomInitBinder {

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        System.out.println("INIT BINDER");
        binder.registerCustomEditor(java.sql.Date.class, new SqlDatePropertyEditor());
        binder.registerCustomEditor(java.sql.Timestamp.class, new SqlTimestampPropertyEditor());
    }

}

我遇到的问题是,我看到它在加载时找到了@InitBinder,但它从未真正进入该方法,因为我没有将“INIT BINDER”打印到System.out。 这意味着自定义编辑器没有注册,因此它们不起作用。 如果我将 initBinder 方法复制并粘贴到我的一个 Controller 中,它对于该特定 Controller 来说效果很好。

1989  INFO [ContainerBackgroundProcessor[StandardEngine[Catalina]]] (RequestMappingHandlerAdapter.java:636) - Detected @InitBinder methods in customInitBinder

知道这里发生了什么吗?

最佳答案

对于遇到此问题的任何人...这就是我为解决该问题所做的操作。

而不是

<context:component-scan base-package="com.myapp.spring"></context:component-scan> 

在我的 root-context.xml 中

我将其更改为我的配置包

<context:component-scan base-package="com.myapp.spring.configuration"></context:component-scan>

然后,我将 @ControllerAdvice 注释的类移至 com.myapp.spring.controllers,并在 servlet-context.xml 中添加

<context:component-scan base-package="com.myapp.spring.controllers">
    <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
</context:component-scan>

关于java - Spring 4 ControllerAdvice 和 InitBinder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21922646/

相关文章:

java - 我们可以在 MySQL 中结合 VALUES 和 SELECT 查询吗

java - 如何使用 java 在 ubuntu 中检测工作站/系统屏幕锁定?

java - PropertyConfigurator.configure 不适用于 spring

java - 在 spring 配置中设置 xml 数据以进行 Junit 测试

spring - 尝试使用本地 Spring Cloud Connector/local_configuration_connector 时找不到合适的云连接器

spring-mvc - 重命名 Spring MVC 模型属性的嵌套属性

java - 如何更改新实例运行时的类型

java - 如何给 Java 产品打补丁?

spring - 配置两个@InitBinder 以使用相同的模型或实体但用于不同的@RequestMappings