WebBindingInitializer won't execute

2019-09-14 10:46发布

How can I make initBinder() method to start every time form loads and submits. This example has responsibility to convert date from String to java.util.Date.

In my servlet-context.xml:

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

Here is my implementation of 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));
    }
}

I didn't made any modifications in controller where ExampleService methods are called. Where I'm wrong?

When I put initBinder() method with @InitBinder annotation to my controller, everything works fine. That doesn't satisfy me beacause I want to have that in external class.

3条回答
对你真心纯属浪费
2楼-- · 2019-09-14 11:28

Make sure you have <mvc:annotation-driven/> included in your configuration and your bean declared prior to it.

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

<mvc:annotation-driven/>

When Spring scans for handlers the first registered handler that fits is used. mvc:annotation-driven registers a few handlers which may be being used in place of your handler.

查看更多
来,给爷笑一个
3楼-- · 2019-09-14 11:31

You must remove or comment out <mvc:annotation-driven/> from your dispatcher-servlet. Documentation

查看更多
迷人小祖宗
4楼-- · 2019-09-14 11:45

The class, AnnotationMethodHandlerAdapter, you use is old and deprecated. You shouldn't use it.

I assume you have <mvc:annotation-driven /> or @EnableWebMvc which registers the recommended and supported RequestMappingHandlerAdapter. You could create a BeanPostProcessor to set the desired property on the RequestMappingHandlerAdapter.

However what you actually should do is create a custom converter and register that using the <mvc:annotation-driven /> namespace. That is the recommended way of doing things and not using a WebBindingInitializer anymore.

查看更多
登录 后发表回答