如何使用.properties文件或数据库中的正则表达式指定Hibernate"@Pattern"注释

Cod*_*key 6 java regex hibernate-validator properties-file

情况:我想基于用户属性执行Hibernate验证(根据用户的帐户数据允许输入的不同验证规则) - 我认为必须可以使用.properties文件来指定特定的正则表达式,但我无法弄清楚出了什么问题:

我当前指定验证正则表达式的方法从特定接口文件中的常量中拉出该正则表达式(将所有内容保持在一起)并将其作为常量插入@Pattern()到每个变量的注释中 - 例如对于变量workPhone:

@Column(name = "WORK_PHONE")
@NotEmpty(message = "{ContactInfo.workPhone.notEmpty}")
@Pattern(regexp = PHONE_NUMBER_PATTERN_SL, message = "{ContactInfo.workPhone.regexp.msg}")
@Size(max = 10, message = "{ContactInfo.workPhone.size}")
protected String                workPhone;
Run Code Online (Sandbox Code Playgroud)

...正则表达式存储在其中static final String PHONE_NUMBER_PATTERN_SL并且所有{ContactInfo.workPhone...}调用都来自.properties文件:

ContactInfo.workPhone.notEmpty=Please enter your phone number.
ContactInfo.workPhone.regexp.msg=Invalid characters entered in phone. Use this format XXX-XXX-XXXX.
ContactInfo.workPhone.size=Phone can not be longer than 10 digits.
Run Code Online (Sandbox Code Playgroud)

不幸的是,这种安排使得验证模式在应用程序范围内(编译),因为我无法想办法为不同的公司,位置,就业位置等的不同用户更改它.为了能够区分基于这个信息,我还想将正则表达式存储在属性文件中,我尝试以这种方式包含它:

ContactInfo.workPhone.regexp=\d{3}-\d{3}-\d{4}
Run Code Online (Sandbox Code Playgroud)

同时在第一个代码清单中的第三行的注释中包含引用:

@Pattern(regexp = "{ContactInfo.workPhone.regexp}", message = "{ContactInfo.workPhone.regexp.msg}")
Run Code Online (Sandbox Code Playgroud)

然后,我会为不同的场合切换属性文件,例如允许/要求非美国电话号码格式.

问题:我可以做我想做的事吗?有没有更好的方法来指定模式(甚至可能允许数据库调用而不是属性文件)?

另外,我不是最好的(因为我从另一个开发人员手中接管),所以如果有人只能指向我关注使用@Pattern注释或其他Hibernate正则表达式验证标记的重点资源,那么可能会给我所需的所有信息.

TL; DR:是否可以对Hibernate模式验证中使用的表达式使用动态设置或修改的值,而不是预定义和预编译的常量?

Gun*_*nar 6

在注释中,您只能引用常量表达式,因此从属性文件或数据库加载值在这里不起作用。

您可以使用Hibernate Validator 4.2 中引入的动态约束声明API,它允许在运行时定义约束。您的示例可能如下所示:

String dynamicPattern = ...;

ConstraintMapping mapping = new ConstraintMapping();
mapping.type( ContactInfo.class )
    .property( "workPhone", FIELD )
    .constraint( new PatternDef().regexp( dynamicPattern ) );

HibernateValidatorConfiguration config = 
    Validation.byProvider( HibernateValidator.class ).configure();
config.addMapping( mapping );

Validator validator = config.buildValidatorFactory().getValidator();
Run Code Online (Sandbox Code Playgroud)