首页 > 其他分享 >让SpringBoot也用上Fluent Validator

让SpringBoot也用上Fluent Validator

时间:2022-09-27 15:58:59浏览次数:76  
标签:SpringBoot fluentvalidator 校验 Fluent Validator br import validate com

前言

在使用SpringBoot的时候经常需要对客户端传入的参数进行合法性的校验,校验的方法基本上都是使用SpringBoot提供的注解,有时候遇上注解不能满足需求的时候还需要在业务逻辑上进行判断。这样根本就没有实现解耦。

使用方法

项目maven引入

<dependency>
    <groupId>com.github.mvallim</groupId>
    <artifactId>java-fluent-validator</artifactId>
    <version>1.10.0</version>
</dependency>

声明实体校验器

package com.a.b.aspect;

import br.com.fluentvalidator.AbstractValidator;
import com.a.b.LoginDto;

import java.util.function.Predicate;

import static br.com.fluentvalidator.predicate.CollectionPredicate.empty;
import static br.com.fluentvalidator.predicate.CollectionPredicate.hasSize;

public class LoginDtoValidator extends AbstractValidator<LoginDto> {
    
    // 支持注入
	@Autowired
    TestService testService;
    
    @Override
    public void rules() {
        setPropertyOnContext("loginDto");

        ruleFor(LoginDto::getUsername)
                .must(s -> s.equals("admin"))
                .withMessage("哈哈,错了")
                // 当发生错误则阻止继续校验
                .critical()
                .must(s-> s.equals(getPropertyOnContext("password",String.class)))
                .withMessage("密码和账号必须要一样的");
    }
}

配置切入点

package com.a.b.aspect;

import br.com.fluentvalidator.context.Error;
import br.com.fluentvalidator.context.ValidationResult;
import com.a.b.LoginDto;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Component
@Aspect
@Slf4j
public class TestAspect {

    @Before("execution(* com.a.b.*.controller.*.*(..)) ")
    public void doBefore(JoinPoint joinPoint){
        Object arg = joinPoint.getArgs()[0];
        ValidationResult validate = new LoginDtoValidator().validate((LoginDto) arg);

        // 获取校验结果
        log.debug("validate {}",validate.isValid());
        StringBuilder stringBuilder = new StringBuilder();

        // 打印并拼接错误信息
        for (Error error : validate.getErrors()) {
            log.debug("error {}",error);
            stringBuilder.append(error.getMessage()).append("\n");
        }

        throw new Exception(stringBuilder.toString());
    }
}

参考资料

项目地址

AOP

标签:SpringBoot,fluentvalidator,校验,Fluent,Validator,br,import,validate,com
From: https://www.cnblogs.com/ykbb/p/16734817.html

相关文章