Autowired Repository is Null in Custom Constraint Validator

前端 未结 4 2065
无人共我
无人共我 2020-12-06 03:17

I have a Spring based webapp. I am using several repository classes with annotations @Repository, @Transactional in my Controllers. That part works fine.

I created a

相关标签:
4条回答
  • 2020-12-06 03:38

    No luck with LocalValidatorFactoryBean. I have done some hack to solve this problem.

    @Component
    public class ServiceUtils
    {
        private static ServiceUtils instance;
    
        @Autowired
        private ListableBeanFactory factory;
    
        @PostConstruct
        public void init()
        {
            instance = this;
        }
    
        public static ListableBeanFactory getFactory()
        {
            return instance.factory;
        }
    }
    
    0 讨论(0)
  • 2020-12-06 03:39

    Which ValidatorFactory are you using. Or to put it another way, hot to you bootstrap Bean Validation? Per default Bean Validation (and Hibernate Validator as reference implentation) does not inject dependencies into ConstraintValidator instances. At least in Bean Validation 1.0.

    To enable dependency injection you have to configure a custom ConstraintValidatorFactory. Spring offers SpringConstraintValidatorFactory which is the default when using LocalValidatorFactoryBean - see http://static.springsource.org/spring/docs/3.0.0.RC3/reference/html/ch05s07.html

    Also, are you using JPA? I assume so, in which case auto validation on life cycle events automatically. Instead of trying to remove event listeners you can just use the property javax.persistence.validation.mode and set it to NONE. I am wondering whether the right validator is used on life cycle based validation.

    It would all depend on your overall Spring configuration and use.

    0 讨论(0)
  • 2020-12-06 03:42

    Do you have an @Component annotation on the DonorTypeExistsConstraintValidator?

    That has killed me in the past.

    0 讨论(0)
  • 2020-12-06 03:43

    Do you pass the validator factory to be used by JPA when performing validation:

    <bean 
        id="entityManagerFactory" 
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="jpaPropertyMap">
            <map>
                <entry 
                    key="javax.persistence.validation.factory"
                    value-ref="validator"/>
                <!-- ... -->
            </map>
        </property>
        <!-- ... -->
    </bean>
    

    That's required since otherwise the default factory (as specified in validation.xml) would be used by JPA.

    0 讨论(0)
提交回复
热议问题