简体   繁体   中英

WebBindingInitializer won't execute

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.

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM