如何在每次表单加载和提交时启动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
方法放到我的控制器上时,一切正常。这不能让我满意,因为我希望在外部课堂上有这个。
答案 0 :(得分:1)
确保您的配置中包含<mvc:annotation-driven/>
,并在之前声明了您的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
注册了一些可能用于代替处理程序的处理程序。
答案 1 :(得分:0)
您必须从调度程序-servlet中删除或注释掉<mvc:annotation-driven/>
。 Documentation
答案 2 :(得分:0)
您使用的类AnnotationMethodHandlerAdapter
是旧的并已弃用。你不应该使用它。
我假设您有<mvc:annotation-driven />
或@EnableWebMvc
注册推荐和支持的RequestMappingHandlerAdapter
。您可以创建BeanPostProcessor
以在RequestMappingHandlerAdapter
上设置所需的属性。
但是,您实际应该做的是创建自定义转换器并使用<mvc:annotation-driven />
命名空间进行注册。这是建议的做事方式而不再使用WebBindingInitializer
。