SpringBoot:没有@Valid注释的验证

SpringBoot: Validation without @Valid annotation

我有一个继承自 AbstractWebSocketHandler 的网络套接字处理程序,用于处理文本消息。我的 DTO 使用 javax.validation.constraints 进行验证。因此,在我的 REST 端点中,我可以简单地使用 @Valid 注释来调用验证器。但是,据我所知,此注释在我的网络套接字处理程序中不可用。如果没有此注释,如何以编程方式调用 SpringBoot 验证器?

此外,是否可以使用 SpringBoot 反序列化器代替 JSON.parseObject 来处理消息?

示例:

import javax.validation.constraints.NotBlank;
import lombok.Data;

@Data
class CustomMessage {
    @NotBlank
    private String text;
}
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import lombok.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

@Component
@Slf4j
public class MyCustomWebSocketHandler extends AbstractWebSocketHandler {
    @Override
    protected void handleTextMessage(@NonNull WebSocketSession session, @NonNull TextMessage message) {
        CustomMessage customMessage = JSON.parseObject(message.getPayload(), CustomMessage.class);
        // Validate the message according to javax.validation annotations and throw MethodArgumentNotValidException if invalid
        log.debug("Received valid message {}", customMessage)
    }
}

您将使用 Validator 来填充 ConstraintViolation 的列表。示例可能如下所示:

public abstract class GenericService<T> {

    protected Validator validator;

    protected void validateDomainRecord(T object, String message) {
        Set<ConstraintViolation<T>> violations = validator.validate(object);
        if(!violations.isEmpty()) {
            throw new ConstraintViolationException(message, violations);
        }
    }
}

在您的情况下,您的代码将如下所示:

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import lombok.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

@Component
@Slf4j
public class MyCustomWebSocketHandler extends AbstractWebSocketHandler {

    private Validator validator;
    
    @Override
    protected void handleTextMessage(@NonNull WebSocketSession session, @NonNull TextMessage message) {
        CustomMessage customMessage = JSON.parseObject(message.getPayload(), CustomMessage.class);
        // Validate the message according to javax.validation annotations and throw MethodArgumentNotValidException if invalid
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        validator = factory.getValidator();            
        Set<ConstraintViolation<CustomMessage>> violations = validator.validate(customMessage);
        if(!violations.isEmpty()) {
            throw new ConstraintViolationException(message, violations);
        }

        log.debug("Received valid message {}", customMessage)
    }
}

看看这么好的tutorial了解更多详情。我想也可以自定义您的验证和异常。