Spring 启动器验证和验证器注入

Spring starter-validation and Validator injection

我创建了简单的非 mvc 项目并添加了 spring-boot-starter-validation 依赖项。当我尝试注入 javax.validation.Validator 时出现错误 org.springframework.beans.factory.NoSuchBeanDefinitionException.

这是否意味着 spring-boot-starter-validation 不提供任何默认验证器,即 LocalValidatorFactoryBean 并且我总是必须像在没有 [=23 的正常项目中一样自己创建它=]开机?

@Component
public class ExampleService{

    @Autowired
    private Validator validator;

    public void someMethod(){
            //validation
    }

}

注入失败,Validator 是来自 javax.validation 还是 org.springframework.validation 包都没有关系。

没有 Beansspring-boot-starter-validation 开箱即用,因此您遇到 NoSuchBeanDefinitionException

的原因

请参阅以下 rationale 直接来自马口的开胃菜:

Previously, the only starter that provided validation was spring-boot-starter-web which included Hibernate Validator and Tomcat's EL implementation. This left users writing non-web applications to figure out the dependencies for themselves. They would sometimes run into difficulties as Hibernate Validator's need for an EL implementation would trip them up.

This commit adds a new starter, spring-boot-starter-validation, which provides both Hibernate Validator and Tomcat's EL implementation. spring-boot-starter-web has been updated to depend on this starter rather than depending on Hibernate Validator directly.