protobuf java class 如何添加接口的数据校验?

我计划使用 springboot + protocol buffer + https 完成一个java后台,但是在使用protocol buffer做接口的数据交换的时候遇到了一个问题,似乎没法添加数据校验。以前自己在写JOPO的时候,可以使用hibernate validator进行数据校验。但是protocol buffer作为接口的数据交换格式的时候却没法找到这样的实现技术。我希望找到能够解决protocol buffer添加数据校验的相关技术,或者其他好的解决方法。

使用Hibernate Validator可以这样做数据校验。

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;

import org.hibernate.validator.constraints.Length;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

public class User {
    
    private long userId;

    @NotNull
    @Length(min=5, max=20)
    private String name;
    
    @NotNull
    private String email;
    
    private String phone;
    
    @Length(min=8, max=16)
    private String password;
    
    @Min(1)
    @Max(150)
    private int age;
    
    public long getUserId() {
        return userId;
    }
    public void setUserId(long userId) {
        this.userId = userId;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    @JsonIgnore
    public String getPassword() {
        return password;
    }
    @JsonProperty
    public void setPassword(String password) {
        this.password = password;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
    @Override
    public String toString() {
        return "User [userId=" + userId + ", name=" + name + ", email=" + email + ", phone=" + phone + ", password="
                + password + ", age=" + age + "]";
    }
}

@RestController
@RequestMapping(value="/validators2", consumes="application/json")
@Validated
public class Volidator2Controller {

    @PostMapping("")
    public Object addUser(@Validated User user) {
        return user;
    }
}

但是protocol却是没有办法完成这个实现。

阅读 3.4k
1 个回答

楼主最后解决了吗?也遇到这个问题,看go语言有验证框架,java的没有搜到,现在想到的办法就是通过protobuf-java-format类库把proto对象转成json,然后再把json转成我们的添加校验规则的对象,然后进行校验。
如果楼住有更好的方法麻烦告知一下,多谢!

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题