我需要根据动态定义的约束和规则检查各种基元类型及其集合的值。这对于检查/监控一组 CNC 机器的返回值是必要的,根据机器/订单/时间/员工/月相等,这些机器可能有不同的可接受值范围。检查还用于确定后续事件生成是否超出关键指标的阈值。
不幸的是,由于无法克服的情况,在数据库中保存值的选项是不可接受的,因此,目前正在考虑以下选项......
选项一:你自己的“自行车”
编写你自己的“自行车”,希望你有足够的资历和经验来开发一个好的库。
选项 2:实施 Bean 验证 API
与第一种选择一样,唯一的区别是“自行车”将根据一定的规则建造,这将有助于避免方形轮子,但使用/可靠性/维护仍然存在问题。
选项 3:Hibernate 验证器
使用 Bean Validation API(Hibernate Validator),可以动态创建规则。用法示例如下:
<!-- Maven dependencies -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.13.Final</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
import org.hibernate.validator.HibernateValidator;
import org.hibernate.validator.cfg.ConstraintMapping;
import org.hibernate.validator.internal.cfg.context.DefaultConstraintMapping;
import org.hibernate.validator.messageinterpolation.ParameterMessageInterpolator;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.valueextraction.ExtractedValue;
import javax.validation.valueextraction.ValueExtractor;
import org.hibernate.validator.cfg.defs.*;
public class App
{
public static void main( final String[] args )
{
try ( ValidatorFactory factory = Validation
.byProvider( HibernateValidator.class )
.configure()
.addMapping( buildPrimitiveConstraintMapping() )
.addValueExtractor( new IntegerValueExtractor() )
.addValueExtractor( new StringValueExtractor() )
.messageInterpolator( new ParameterMessageInterpolator() )
.buildValidatorFactory() )
{
Validator validator = factory.getValidator();
validator.validate( 7 )
.stream()
.map( ConstraintViolation::getMessage )
.forEach( System.out::println );
validator.validate( "" )
.stream()
.map( ConstraintViolation::getMessage )
.forEach( System.out::println );
}
catch ( Exception e )
{
e.printStackTrace();
}
}
private static ConstraintMapping buildPrimitiveConstraintMapping()
{
ConstraintMapping mapping = new DefaultConstraintMapping();
mapping
.type( Integer.class )
.constraint( new NotNullDef() )
.constraint( new MinDef().value( 18 ) )
.constraint( new MaxDef().value( 50 ) );
mapping
.type( String.class )
.constraint( new NotNullDef() )
.constraint( new NotBlankDef() );
return mapping;
}
// Value extractor for Integer
public static class IntegerValueExtractor
implements
ValueExtractor<@ExtractedValue(type = Integer.class) Integer>
{
@Override
public void extractValues(
Integer originalValue,
ValueReceiver receiver )
{
receiver.value( null, originalValue );
}
}
// Value extractor for String
public static class StringValueExtractor
implements
ValueExtractor<@ExtractedValue(type = String.class) String>
{
@Override
public void extractValues(
String originalValue,
ValueReceiver receiver )
{
receiver.value( null, originalValue );
}
}
}
习惯上如何“根据风水”解决此类问题?所选库对于解决任务/问题是否多余?