使用Spring 4和消息插值配置在ConstraintValidator中注入存储库

dre*_*nda 8 spring hibernate hibernate-validator spring-validator

我创建了一个小示例项目,以显示我在Spring Boot验证配置及其与Hibernate集成时遇到的两个问题.我已经尝试过我发现的有关该主题的其他回复,但遗憾的是它们对我不起作用或者要求禁用Hibernate验证.

我想使用自定义的Validator实现ConstraintValidator<ValidUser, User>并注入我的UserRepository.同时我想保持Hibernate的默认行为,在更新/持久化期间检查验证错误.

我在这里写的是应用程序的完整主要部分.

自定义配置 在这个类中,我使用自定义设置自定义验证器MessageSource,因此Spring将从文件中读取消息resources/messages.properties

@Configuration
public class CustomConfiguration {

    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasenames("classpath:/messages");
        messageSource.setUseCodeAsDefaultMessage(false);
        messageSource.setCacheSeconds((int) TimeUnit.HOURS.toSeconds(1));
        messageSource.setFallbackToSystemLocale(false);
        return messageSource;
    }

    @Bean
    public LocalValidatorFactoryBean validator() {
        LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean();
        factoryBean.setValidationMessageSource(messageSource());
        return factoryBean;
    }

    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        MethodValidationPostProcessor methodValidationPostProcessor = new MethodValidationPostProcessor();
        methodValidationPostProcessor.setValidator(validator());
        return methodValidationPostProcessor;
    }

}
Run Code Online (Sandbox Code Playgroud)

如果不是自定义验证器,那么bean没什么特别之处@ValidUser

@ValidUser
@Entity
public class User extends AbstractPersistable<Long> {
    private static final long serialVersionUID = 1119004705847418599L;

    @NotBlank
    @Column(nullable = false)
    private String name;

    /** CONTACT INFORMATION **/

    @Pattern(regexp = "^\\+{1}[1-9]\\d{1,14}$")
    private String landlinePhone;

    @Pattern(regexp = "^\\+{1}[1-9]\\d{1,14}$")
    private String mobilePhone;

    @NotBlank
    @Column(nullable = false, unique = true)
    private String username;

    @Email
    private String email;

    @JsonIgnore
    private String password;

    @Min(value = 0)
    private BigDecimal cashFund = BigDecimal.ZERO;

    public User() {

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLandlinePhone() {
        return landlinePhone;
    }

    public void setLandlinePhone(String landlinePhone) {
        this.landlinePhone = landlinePhone;
    }

    public String getMobilePhone() {
        return mobilePhone;
    }

    public void setMobilePhone(String mobilePhone) {
        this.mobilePhone = mobilePhone;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public BigDecimal getCashFund() {
        return cashFund;
    }

    public void setCashFund(BigDecimal cashFund) {
        this.cashFund = cashFund;
    }

}
Run Code Online (Sandbox Code Playgroud)

自定义验证器 这是我尝试注入存储库的地方.如果不禁用Hibernate验证,则存储库始终为null.

    public class UserValidator implements ConstraintValidator<ValidUser, User> {
    private Logger log = LogManager.getLogger();

    @Autowired
    private UserRepository userRepository;

    @Override
    public void initialize(ValidUser constraintAnnotation) {
    }

    @Override
    public boolean isValid(User value, ConstraintValidatorContext context) {
        try {
            User foundUser = userRepository.findByUsername(value.getUsername());

            if (foundUser != null && foundUser.getId() != value.getId()) {
                context.disableDefaultConstraintViolation();
                context.buildConstraintViolationWithTemplate("{ValidUser.unique.username}").addConstraintViolation();

                return false;
            }
        } catch (Exception e) {
            log.error("", e);
            return false;
        }
        return true;
    }

}
Run Code Online (Sandbox Code Playgroud)

messages.properties

#CUSTOM VALIDATORS
ValidUser.message = I dati inseriti non sono validi. Verificare nuovamente e ripetere l'operazione.
ValidUser.unique.username = L'username [${validatedValue.getUsername()}] è già stato utilizzato. Sceglierne un altro e ripetere l'operazione.

#DEFAULT VALIDATORS
org.hibernate.validator.constraints.NotBlank.message = Il campo non può essere vuoto

# === USER ===
Pattern.user.landlinePhone = Il numero di telefono non è valido. Dovrebbe essere nel formato E.123 internazionale (https://en.wikipedia.org/wiki/E.123)
Run Code Online (Sandbox Code Playgroud)

在我的测试中,您可以尝试使用源代码,我有两个问题:

  1. UserValidator如果我不禁用Hibernate验证,则注入的存储库为null(spring.jpa.properties.javax.persistence.validation.mode = none)
  2. 即使我禁用了Hibernate验证器,我的测试用例也会失败,因为有些东西会阻止Spring对验证消息使用默认的字符串插值,这些消息应该类似于[Constraint].[class name lowercase].[propertyName].我不想像这样使用值元素的约束注释,@NotBlank(message="{mycustom.message}")因为我没有看到考虑到它有自己的插值对应的点,我可以利用它...这意味着更少的编码.

我附上了代码 ; 您可以运行Junit测试并查看错误(启用Hibernate验证,检查application.properties).

我究竟做错了什么?我该怎么做才能解决这两个问题?

======更新======

只是为了澄清,阅读Spring验证文档https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#validation-beanvalidation-spring-constraints他们说:

默认情况下,LocalValidatorFactoryBean配置一个SpringConstraintValidatorFactory,它使用Spring创建ConstraintValidator实例.这允许您的自定义ConstraintValidators像其他任何Spring bean一样受益于依赖注入.

正如您所看到的,ConstraintValidator实现可能与其他任何Spring bean一样具有@Autowired的依赖关系.

在我的配置类中,我在LocalValidatorFactoryBean编写时创建了我的.

另一个有趣的问题是这个这个,但我没有运气.

======更新2 ======

经过大量的研究,似乎用Hibernate验证器没有提供注入.

我找到了几种可以做到这一点的方法:

第一路

创建此配置类:

 @Configuration
public class HibernateValidationConfiguration extends HibernateJpaAutoConfiguration {

    public HibernateValidationConfiguration(DataSource dataSource, JpaProperties jpaProperties,
            ObjectProvider<JtaTransactionManager> jtaTransactionManager,
            ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers) {
        super(dataSource, jpaProperties, jtaTransactionManager, transactionManagerCustomizers);
    }

    @Autowired
    private Validator validator;

    @Override
    protected void customizeVendorProperties(Map<String, Object> vendorProperties) {
        super.customizeVendorProperties(vendorProperties);
        vendorProperties.put("javax.persistence.validation.factory", validator);
    }
}
Run Code Online (Sandbox Code Playgroud)

第二种方式

创建一个实用程序bean

    @Service
public class BeanUtil implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        context = applicationContext;

    }

    public static <T> T getBean(Class<T> beanClass) {

        return context.getBean(beanClass);

    }

}
Run Code Online (Sandbox Code Playgroud)

然后在验证器初始化中:

@Override
 public void initialize(ValidUser constraintAnnotation) {
 userRepository = BeanUtil.getBean(UserRepository.class);
 em = BeanUtil.getBean(EntityManager.class);
 }
Run Code Online (Sandbox Code Playgroud)

很重要

在这两种情况下,为了使其工作,您必须以这种方式"重置"实体管理器:

@Override
public boolean isValid(User value, ConstraintValidatorContext context) {
    try {
        em.setFlushMode(FlushModeType.COMMIT);
        //your code
    } finally {
        em.setFlushMode(FlushModeType.AUTO);
    }
}
Run Code Online (Sandbox Code Playgroud)

无论如何,我不知道这是否真的是一种安全的方式.可能根本不是访问持久层的好方法.

小智 0

如果您确实需要在验证器中使用注入,请尝试@Configurable在其上添加注释:

@Configurable(autowire = Autowire.BY_TYPE, dependencyCheck = true)
public class UserValidator implements ConstraintValidator<ValidUser, User> {
    private Logger log = LogManager.getLogger();

    @Autowired
    private UserRepository userRepository;

    // this initialize method wouldn't be needed if you use HV 6.0 as it has a default implementation now
    @Override
    public void initialize(ValidUser constraintAnnotation) {
    }

    @Override
    public boolean isValid(User value, ConstraintValidatorContext context) {
        try {
            User foundUser = userRepository.findByUsername( value.getUsername() );

            if ( foundUser != null && foundUser.getId() != value.getId() ) {
                context.disableDefaultConstraintViolation();
                context.buildConstraintViolationWithTemplate( "{ValidUser.unique.username}" ).addConstraintViolation();

                return false;
            }
        } catch (Exception e) {
            log.error( "", e );
            return false;
        }
        return true;
    }

}
Run Code Online (Sandbox Code Playgroud)

从文档到该注释:

将类标记为符合 Spring 驱动配置的条件

所以这应该可以解决你的空问题。为了让它工作,你需要配置 AspectJ...(检查如何在 Spring 中使用 @Configurable)