javax的@Valid注解使用场景

javax's @Valid annotation usage scenario

是否可以在以下情况下使用 @Valid (javax.validation.Valid)

import com.fasterxml.jackson.databind.ObjectMapper;
import javax.validation.Valid;
import com.incident.tool.model.IncidentModel;

@Service
public class JsonStringToObjectConverter {

    public IncidentModel convertToObject(String json) throws JsonMappingException, JsonProcessingException {
        @Valid
        IncidentModel incidentModel = new ObjectMapper().readValue(json, IncidentModel.class);
        return incidentModel ;
    }
}

这里 JsonStringToObjectConvertor 以字符串的形式接收 JSON 并将其映射到 IncidentModel class。我以下面的方式在 IncidentModel 中定义了一些验证,我想在进一步处理之前验证 IncidentModelObjectMapper 映射的字段:

@Component
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class IncidentModel extends IncidentInfo {
    @NotEmpty
    private String empId;

    @NotEmpty
    @Size(min = 2, max = 30)
    private String empName;

    @NotEmpty
    private String title;
    private String description;
    private String assignedTo;
    private String severity;
    private String incidentNumber;
    private String dateCreated;
    private String dateClosed;
    private String closingNotes;
}

上面的格式好像不行,在convertToObject方法中使用@Valid有什么替代方法吗?

感谢您的帮助。

您可以进行如下操作:

@Service
public class JsonStringToObjectConverter {

    public IncidentModel convertToObject(String json) throws JsonMappingException, JsonProcessingException {
        IncidentModel incidentModel = new ObjectMapper().readValue(json, IncidentModel.class);
        
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<IncidentModel>> errors = validator.validate(incidentModel);
        
        return incidentModel;
    }
}

然后您可以对其进行优化并创建 JsonStringToObjectConverterValidatorFactory factoryValidator validator 实例变量,这样您就不会在每次调用 convertToObject 方法时都重新创建它们。