Spring-Boot如何正确注入javax.validation.Validator [英] Spring-Boot How to properly inject javax.validation.Validator

查看:1158
本文介绍了Spring-Boot如何正确注入javax.validation.Validator的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用JSR-303(hibernate-validator)验证模型时,我遇到了将 Validator 注入spring应用程序bean的问题

I've got a problem injecting the Validator into the spring application bean when attempting to validate a model using JSR-303 (hibernate-validator)

我的主要配置类是:

@EnableAutoConfiguration
@EnableWebMvc // <---
@EnableJpaRepositories("com.example")
@EntityScan("com.example")
public class MainConfiguration {

根据javadocs:

According to the javadocs:

/**
 * Provide a custom {@link Validator} instead of the one created by default.
 * The default implementation, assuming JSR-303 is on the classpath, is:
 * {@link org.springframework.validation.beanvalidation.LocalValidatorFactoryBean}.
 * Leave the return value as {@code null} to keep the default.
 */
Validator getValidator();

Hibernate-validator在类路径上。
我正在尝试将其注入存储库:

Hibernate-validator is on the classpath. I'm trying to inject it into the Repository:

@Repository
public class UserRepositoryImpl implements UserRepositoryCustom    {

    @Autowired
    private Validator validator;

抛出异常:

 No qualifying bean of type [javax.validation.Validator] found for dependency:

更新:

这方面的部分解决方法是在主配置类中定义:

The partial work-around for this is to define this in the main configuration class:

  @Bean
    public Validator validator() {

        return new org.springframework.validation.beanvalidation.LocalValidatorFactoryBean();
    }

但是集成测试(需要 org。 springframework.test.context.web.WebAppConfiguration; 注释并使用验证逻辑)失败。

But integration tests (the ones which require org.springframework.test.context.web.WebAppConfiguration; annotation and use validation logic) fail.

推荐答案

您需要声明一个类型为 LocalValidatorFactoryBean 的bean,如下所示:

You need to declare a bean of type LocalValidatorFactoryBean like this:

<bean id="validator"
    class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>

XML中的

in XML or

@Bean
public javax.validation.Validator localValidatorFactoryBean() {
   return new LocalValidatorFactoryBean();
}

部分Spring文档包含所有细节

This part of the Spring documentation has all the details

这篇关于Spring-Boot如何正确注入javax.validation.Validator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆