我正在尝试使用 @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/