Spring 引导应用程序启动时,JSR-303 注释不验证 bean 属性

JSR-303 annotations do not validate bean properties when Spring Boot application starts

我需要在启动时验证属性 bean,如果验证失败,应用程序将无法启动。

我有一个包含环境变量提供的配置的 bean:

@Component
public class AdminConfig
{
    @NotNull( message = "username can't be null")
    @NotEmpty( message = "username can't be empty")
    @Value(value="#{environment.username}")
    /** username to the admin portal **/
    private String username;

    @NotNull(message = "password can't be null")
    @NotEmpty(message = "password can't be empty")
    @Value(value="#{environment.password}")
    /** password to the admin portal **/
    private String password;
}

我有一个 driver class:

/**
 * Driver class.
 */
@EnableAutoConfiguration
public class Main {

    /**
     * Driver method.
     * @param args Command line arguments.
     */
    public static void main(final String[] args)  {
        SpringApplication.run(Main.class, args);

    }
 }

我有以下 POM 条目:

<dependencies>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>
        <!-- Validation annotations -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>
</dependencies>

当我在没有设置环境变量的情况下启动应用程序时,AdminConfig bean 被创建但是验证没有触发,应用程序启动了。

我 expect/require 由于验证失败,应用程序无法启动。

bean 验证只有在请求时才会发生。 bean 实例化不请求验证。

The 3.8.2. Configuring a Bean Validation Provider section of the Spring documentation implies that a Validator 是有效实例所必需的:

Spring provides full support for the Bean Validation API. This includes convenient support for bootstrapping a JSR-303/JSR-349 Bean Validation provider as a Spring bean. This allows for a javax.validation.ValidatorFactory or javax.validation.Validator to be injected wherever validation is needed in your application.

请注意,在某些特定情况下,不需要您 explictly/programmatically 就请求验证。例如,当您将实体保存在 Spring JPA 存储库中或调用接受带有 @Valid 注释的参数的 Spring MVC/Rest bean 方法时,就是这种情况。

在您的情况下,您可以在通过注入和使用 Validator bean(可用于 Spring 使用您在 pom.xml) :

import java.util.Set;

import javax.annotation.PostConstruct;
import javax.validation.ConstraintViolation;
import javax.validation.ValidationException;
import javax.validation.Validator;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AdminConfig{

    @Autowired
    private Validator validator;

    @NotNull( message = "username can't be null")
    @NotEmpty( message = "username can't be empty")
    private String username;

    @NotNull(message = "password can't be null")
    @NotEmpty(message = "password can't be empty")
    private String password;

    @PostConstruct
    public void init() {
        final Set<ConstraintViolation<AdminConfig>> validationErrors = validator.validate(this);
        if (!validationErrors.isEmpty()) {
            throw new ValidationException("validation errors for adminConfig bean : " + validationErrors);
        }
    }
}

在 AdminConfig 中使用 @Validated 注释