集成到CustomValidator实现中的任何bean始终为null。我使用的是Spring Boot 2,应用程序是REST API,我没有使用MVC。
到目前为止,我已经尝试了所有我读过的有关此事的尝试。
this topic here for example did not work for me
我是否应该验证?,我已经坚持了两天。
这是我的Config类:
@Configuration
public class Beans {
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:idiomas/idioma");
messageSource.setUseCodeAsDefaultMessage(true);
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
@Bean
public LocaleResolver localeResolver() {
AcceptHeaderLocaleResolver resolver = new AcceptHeaderLocaleResolver();
resolver.setDefaultLocale(new Locale("es"));
return resolver;
}
@Bean
public LocalValidatorFactoryBean getValidator() {
LocalValidatorFactoryBean validatorFactoryBean = new LocalValidatorFactoryBean();
validatorFactoryBean.setValidationMessageSource(messageSource());
return validatorFactoryBean;
}
@Bean
public CommonsRequestLoggingFilter logFilter() {
CommonsRequestLoggingFilter filter = new CommonsRequestLoggingFilter();
filter.setIncludeQueryString(true);
filter.setIncludePayload(true);
filter.setMaxPayloadLength(10000);
filter.setIncludeHeaders(true);
filter.setAfterMessagePrefix("REQUEST: ");
return filter;
}
}
我的CustomValidator看起来像这样:
public class AlmacenValidator implements ConstraintValidator {
@Autowired
private AlmacenService servicio;
@Autowired
private ApplicationContext contexto;
@Override
public void initialize(AlmacenValido constraintAnnotation) {
}
@Override
public boolean isValid(Almacen item, ConstraintValidatorContext context) {
//Database calls
}
JPA实体:
@Entity
@AlmacenValido
@Table(name = "almacenes")
public class Almacen {
//Entity fields
}
注释:
@Documented
@Retention(RUNTIME)
@Target({ TYPE, FIELD, ANNOTATION_TYPE, PARAMETER })
@Constraint(validatedBy = AlmacenValidator.class)
public @interface AlmacenValido {
String message() default "{validacion.almacen}";
Class[] groups() default {};
Class[] payload() default {};
}
答案 0 :(得分:0)