我尝试通过Hibernate Validator验证bean。它应该是可编程的,并且基于JSON配置文件。 数据模型:
class A {
field,
other fields
}
class B {
class A a,
other fields
}
class C {
class A a,
other fields
}
class D {
class B b,
class C c,
other fields
}
根据JSON配置文件验证D。 配置文件要验证以下内容: D.b.a.字段不应为null。 D.c.a.字段为空。
使用程序方式,我将验证设置如下:
constraintMapping
.type( D.class )
.property( "b", FIELD )
.constraint( new NotNullDef() )
.valid()
.type( B.class )
.property( "a", FIELD )
.constraint( new NotNullDef() )
.valid()
.type ( A.class )
.property( "field", FIELD )
.constraint( new NotNullDef() );
现在,A.field已设置为非null验证程序,但是问题是,现在D.c.a.filed也不能为null。
这只是一个例子,我绝对不想更改数据模型。
答案 0 :(得分:0)
在约束级别使用组可能会帮助您解决问题。要将组添加到约束中,您只需要调用group
方法并传递应在其中包含约束的组列表即可:
constraintMapping
.type( D.class )
.property( "b", FIELD )
.constraint( new NotNullDef().groups( SomeGroup.class )
.valid()
然后您可以为不同的“验证路径”创建不同的组,并在验证对象时使用它们。如果您的验证配置是完全动态的,则Thant可能效果不佳。有关组的更多信息,请参见doc。
答案 1 :(得分:0)
@ mark-o,我测试了以下解决方案,但失败了。 它将同时验证GroupB和GroupC的field1和field2, 但我的期望是仅对GroupB而不是GroupC验证field1, 并仅对GroupC而不对GroupB验证field2。
对A类(具有field1和field2)进行少许更改,并为B类和C类使用的A类添加包装。
using System;
using System.Diagnostics;
using System.Windows.Forms;
using CobblestoneMgmt.Forms;
using ConfigManagement;
using CodeLibrary.ConsoleFunctions;
using Xtensions.CmdlineArgumentMgmt;
namespace AppMgmt
{
static class Program
{
/// <summary>The main entry point for the application.</summary>
[STAThread]
static void Main(string[] _args)
{
ArgumentsMgt args = new ArgumentsMgt(_args);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if (args.Count == 0)
{
// Run it as a WindowsForms application.
Application.Run(new AppManagement());
}
else
{
Console.OutputEncoding = System.Text.Encoding.Unicode;
//Run it as a Console application.
if (args.HasSwitch("install"))
{
if ((args.Count==1) || args["install"].HasValue("guided") || args.HasSwitch("guided"))
Application.Run(new Installation());
if (args.HasSwitch("regedit"))
{
if (args["regedit"].HasValue("ShowConfig"))
{
IniFile config = IniFile.FetchResourceFile("AppMgmt.ExternalResources.DefaultConfig.ini");
Con.Write(config.ToString());
}
}
}
Con.WaitPrompt();
}
}
}
}