java - Spring 验证: Difference between validation annotations in Class Attributes VS Constructor Parameters

标签 java spring spring-boot validation javax.validation

我有以下模型对象:

@Validated
public class Message implements Serializable {
    private static final long serialVersionUID = 9028633143475868839L;
    @NonNull
    @Size(min = 6, max = 6)
    @Pattern(regexp = "[\\d]{6}")
    private String id;
    @NotNull
    @Size(min = 1, max = 200)
    private String title;
    @NotNull
    @Size(min = 1, max = 1000)
    private String message;
    @NotEmpty
    private String type;
    private String publishId;

    public Message(){
    }

    public Message(@NonNull @Size(min = 6, max = 6) @Pattern(regexp = "[\\d]{6}") String id, @NotNull @Size(min = 1, max = 200) String title, @NotNull @Size(min = 1, max = 1000) String message, @NotEmpty String type, String publishId) {
        this.id = id;
        this.title = title;
        this.message = message;
        this.type = type;
        this.publishId = publishId;
    }
}

在此 Message 类中,每个字段都用验证约束进行注释。此外,每当我在 IDEA IDE 中自动生成构造函数时,注释也会自动附加到构造函数参数中。

我的问题是:如果我从构造函数参数字段/对象属性中删除这些约束,是否会产生任何副作用?? p>

这些验证在内部如何运作?

我使用 javax.validation.Validator::validate 进行验证。

如果可能,请附上链接作为引用

最佳答案

如果删除构造函数中的约束,不会有任何副作用。字段变量中的约束仍然有效。

您甚至不需要创建构造函数。 Spring boot 会自动注入(inject)您的 Message 类,因此您只需将其传递到 Controller 中即可。 Controller/RestController 中的示例用法:

ResponseEntity<String> addMessage(@Valid @RequestBody Message message) {
        // If message is not valid. This will throw an exception which you can catch in the GlobalExceptionHandler.
        return ResponseEntity.ok("Message is valid");
    }

关于java - Spring 验证: Difference between validation annotations in Class Attributes VS Constructor Parameters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57178329/

相关文章:

java - 如何创建 Sonar 规则来解析 Java 中的自定义 XML 文件?

java - Maven Spring 依赖库

java - 如何从applicationContext.xml中的bean读取值?

java - Spring 启动+Maven : repositoryFactoryBean not found

json - 可以使用 RestTemplate PUT 传递我自己的对象

spring-security - 多个@EnableGlobalMethodSecurity 注解

java - 警告 : No mapping found for HTTP request with URI [] in DispatcherServlet with name 'dispatcher'

java - 模拟用户点击网页[JAVA]

java - 我们应该如何在 Java 中使用 vector ,就像在 C++ 中使用 vector 一样?

spring - Grails 从依赖项中排除 jar