@Autowired bean null in ConstraintValidator when invoked by Sessionfactory.getCurrentSession.merge

后端 未结 2 1611
星月不相逢
星月不相逢 2021-02-11 08:48

I have just implemented Bean Validation with Hibernate.

If I call the validator explicitly it works as expected and my @Autowired DAO bean that connects to the DB is inj

2条回答
  •  野性不改
    2021-02-11 09:00

    You can use the following method provided by Spring framework since 2.5.1

    SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
    

    it's much cleaner since you don't have to set any listener/property across your application.

    You code will look like this:

    public class ValidUniqueUserEmailValidator implements ConstraintValidator, Serializable {
    
        private static final long serialVersionUID = 1L;
    
        @Autowired
        private UserDAO userDAO;
    
        @Override
        public void initialize(ValidUniqueUserEmail constraintAnnotation) {
            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
        }
    
        @Override
        public boolean isValid(Object value, ConstraintValidatorContext context) {
            boolean isValid = true;
            if (value instanceof String) {
                String email = value.toString();
                if (email == null || email.equals("")) {
                    isValid = false;
                }else{
                    User user = new User();
                    user.setEmail(email);
                    isValid = (userDAO.countByEmail(user) > 0);
                }
            }
            return isValid;
    
        }
    
    }
    

    Hope it helps you guys out

提交回复
热议问题