How to stop DefaultListableBeanFactory from implicitly creating LocalValidatorFactoryBean instance

大城市里の小女人 提交于 2019-12-11 18:51:13

问题


I am using Spring 3.1 and have the following spring config where I explicitly create LocalValidatorFactoryBean using my own ValidationMessageSource. I have Hibernate Validator 4.1 in my class path.

<bean id="messageSource"
      class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basenames">
        <list>
            <value>ValidatorMsgID</value>
        </list>
    </property>
</bean>

<bean id="validator"
      class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
    <property name="validationMessageSource" ref="messageSource"/>
</bean>

<bean class="org.springframework.validation.beanvalidation.MethodValidationPostProcessor"/>

However I noticed that the LocalValidatorFactoryBean is being created twice by hitting a debug in classes afterPropertiesSet method. The first time is for the explicite bean that I defined in the spring config, however following that the same class is instantiated implicitly again by DefaultListableBeanFactory class - obviously this time with no validationMessageSource. Therefore it seems that when Spring does make use of the LocalValidatorFactoryBean its using the one with the default Hibernates messagesource rather than the one I have specified.

Ok, looking into this a bit further its seems that this is caused by mvc:annotation-driven I have in the spring config. Any pointers would still help


回答1:


Ok, I got it sorted eventually by adding the validator attribute to "mvc:annotation-driven". This is how my final spring config looks

<bean id="messageSource"
      class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basenames">
        <list>
            <value>com.mycompany.msgs.ValidatorMsgID</value>
        </list>
    </property>
</bean>

<bean id="validator"
      class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
    <property name="messageInterpolator">
        <bean class="org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator">
            <constructor-arg index="0">
                <bean class="org.springframework.validation.beanvalidation.MessageSourceResourceBundleLocator">
                    <constructor-arg index="0" ref="messageSource"/>
                </bean>
            </constructor-arg>
        </bean>
    </property>
</bean>

<bean class="org.springframework.validation.beanvalidation.MethodValidationPostProcessor">
    <property name="validator" ref="validator"/>
</bean>

<mvc:annotation-driven validator="validator"/> 


来源:https://stackoverflow.com/questions/9348648/how-to-stop-defaultlistablebeanfactory-from-implicitly-creating-localvalidatorfa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!