Hibernate/Spring 带有自动装配存储库的自定义验证

Hibernate/Spring Custom Validations w/ Autowired repository

我正在构建一个自定义约束验证器,并不断得到 HV000028: Unexpected exception during isValid call.]

奇怪的是 findById 方法 returns 并在控制台上打印了正确的数据,但出现了上述错误。我怎样才能让它没有错误?

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@Validated
public class invitecontroller {

    @PostMapping("/v1/invite")
    public void invite(@Valid @RequestBody invite invite){
    }

}
@inviteconstraints
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class invite {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long inviteid;

    private String type;
    private Long propertyid;
    private Date moveindate;
    
    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name = "inviteid")
    private List<applicant> applicants;

}
public class inviteconstraint implements ConstraintValidator<inviteconstraints, invite> {
  
    @Autowired propertyrepository propertyrepository;

    @Override
    public boolean isValid(invite invite, ConstraintValidatorContext context) {
        
       
        property property = propertyrepository.findById(1L).get();  

        ^^^ **Error Happens Here** ^^^


        return true;
    }

    @Override 
    public void initialize(inviteconstraints constraintannotation) {
    }

}
@Target(  { ElementType.TYPE } )  
@Retention(RetentionPolicy.RUNTIME)  
@Constraint(validatedBy = inviteconstraint.class)
public @interface inviteconstraints {
 
    public String message() default "Validator Failed"; 
    public Class<?>[] groups() default {};  
    public Class<? extends Payload>[] payload() default {}; 
    
}

自动装配在这种情况下不起作用,因此您在这 (propertyRepository) 点遇到错误。 为了使自动装配工作,您需要进行另一个配置。使用此功能后,自动装配将成功进行。

@Component
public class HibernateValidatorCustomizer implements HibernatePropertiesCustomizer {

    private final ObjectProvider<Validator> provider;

    public HibernateValidatorCustomizer(ObjectProvider<Validator> provider) {
        this.provider = provider;
    }

    public void customize(Map<String, Object> hibernateProperties) {
        Validator validator = provider.getIfUnique();
        if (validator != null) {
            hibernateProperties.put("javax.persistence.validation.factory", validator);
        }
    }
}