首页 > 解决方案 > 休眠验证 - 自动装配返回 null

问题描述

环顾四周后,我找不到任何好的解决方案。

我的 autowired 没有按预期工作,它返回 null。我已经在其他类中自动装配了这个特定的类,它可以工作,所以它只在约束验证器类中不起作用。

用户服务类

@Service
public class UserService {

    @Autowired
    private UserRepository userRep;
    
    public void addUser(User user) {
        userRep.save(user);
    }
    
    
    public void deleteUser(long userId) {
        userRep.deleteById(userId);
    }
    
    public List<User> retrieveAllUsers(){
        Iterable<User>temp =userRep.findAll();
        List<User>allUsers = null;
        temp.forEach(allUsers::add);
        return allUsers;
    }
    
    public boolean searchByEmail(String email) {
        return userRep.findByEmail(email);
    }
    
    public void updateUser(User user) {
        userRep.save(user);
    }
}

注解接口类

 @Target(ElementType.FIELD) 
    //When will the annotation be processed compilation, runtime etc
    @Retention(RetentionPolicy.RUNTIME)
    //Where is the logic
    @Constraint(validatedBy = EmailValidator.class)
    @Documented
    public @interface ValidEmail {
        
        //Error message
        String message() default "Invalid email";
        //Required for annotation
        Class<?>[] groups() default {};
        Class<? extends Payload>[] payload() default {};
        
    }

注释逻辑类。这里的 autowired 返回 null

public class EmailValidator implements ConstraintValidator<ValidEmail, String> {

    @Autowired
    private UserService service;
    //Actual place to place the logic to check if the data is valid or not
    @Override
    public boolean isValid(String email, ConstraintValidatorContext context) {
        if (email == null) {
        return false;
        }
        
        List<User> users = service.retrieveAllUsers();
        if (users.size() > 0) { 
        return Pattern.matches("(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])", email)
                && service.searchByEmail(email);
        }
        
        else {
            return Pattern.matches("(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])", email);
        }
        }
        
    
    
    @Override
    public void initialize(ValidEmail validEmail) {
        validEmail.message();
    }

}

主要的

@SpringBootApplication
@ComponentScan(basePackages = {
        "com.Alex.Mains", "com.Alex.UserPackage", "com.Alex.Flights", "com.Alex.Security"
})
@EntityScan( basePackages = {"com.Alex.UserPackage", "com.Alex.Flights"})
@EnableJpaRepositories({"com.Alex.UserPackage", "com.Alex.Flights"})
public class JpaApplication {

    public static void main(String[] args) {
        SpringApplication.run(JpaApplication.class, args);
    }
    
//  @Bean
//  public Validator validator(final AutowireCapableBeanFactory beanFactory) {
//
//      ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
//              .configure()
//              .constraintValidatorFactory(new SpringConstraintValidatorFactory(beanFactory))
//              .buildValidatorFactory();
//
//      return validatorFactory.getValidator();
//  }
    
}

在此处输入图像描述

编辑:试过@Componenet

标签: springspring-boothibernatespring-mvchibernate-validator

解决方案


编辑:我的建议

代替自定义验证器,使用现有的 @EMail 和唯一约束:

@Entity
public class User {
  // ...your properties

  @Email
  @Column(unique = true)
  private String email.

  // Rest of class...
}

老的:

所以,首先:

List<User> users = service.retrieveAllUsers();
    if (users.size() > 0) { 

您正在从数据库中获取所有用户,只是为了检查是否存在任何用户?这是非常非常低效的。如果您已经在使用 Spring Data,您可以这样做

@Query("SELECT COUNT(*) > 0 FROM Users")
boolean anyExists();

此外,您的 Service 不会被注入,因为EmailValidator它是 POJO(普通的旧 java 对象)而不是 Spring 托管组件。如果你用@Component@ServiceSpring 注释它,它将处理注入。

但我不建议这样做。我不确定您的确切用例是什么,但验证器通常用于实体,因此,在创建或更新实体时会调用它们。在这些情况下,您不想发出额外的查询。

就像我说的,我不知道你到底想要实现什么,但你可以使用现有的@Email验证器(你甚至可以提供一个带有regexp 属性的自定义正则表达式)。


推荐阅读