可以将 Drools 配置为将规则应用于插入对象字段中包含的对象吗?

Can Drools be configured to apply rules to the objects contained in the inserted objects fields?

我有一套复杂的规则要在 Drools 中实施,我正在努力避免重复的规则。例如,我有一个 ForeignPerson class 被另外两个 classes 使用。

public class ForeignPerson {
  private String name;
  private String country;
}

public class Owner {
  private Individual individual;
  private ForeignPerson foreignPerson;
}

public class Beneficiary {
  private Individual individual;
  private ForeignPerson foreignPerson;
}

在 ForeignPerson 的每个实例中,国家字段必须是 "USA"。我希望能够做到 kieSession.insert(owner);,如果 ForeignPerson 字段不为空,请检查 ForeignPerson 规则以及所有者规则。

ForeignPerson.drl 规则文件如:

rule "R001: Country must == USA"
  when 
    ForeignPerson(country != "USA")
  then 
    System.out.println("Country must be USA");
end

Owner.drl 规则文件如:

rule "R001: Foreign Person must exist"
  when 
    Owner(foreignPerson == null)
  then 
    System.out.println("foreignPerson must not be null");
end

我不想像下面这样写 Owner.drl 文件,因为它会导致很多重复的规则。

rule "R001: Foreign Person must exist"
  when 
    Owner(foreignPerson == null)
  then 
    System.out.println("foreignPerson must not be null");
end

rule "R002: Foreign Person country must be USA"
  when 
    Owner(foreignPerson != null, foreignPerson.getCountry() != "USA")
  then 
    System.out.println("foreignPerson must have country USA");
end

这是否可能或者是单独注入对象的唯一方法?

此规则确定外国人来自美国。

rule "from the US"
when 
  $foreignPerson: ForeignPerson( country == "USA" )
then
end

您可以使用它来检查所有者事实:

rule "owner from the US"
  extends "from the US"
when
  Owner( foreignPerson == $foreignPerson )
then
  // ... owner is from the US
end

受益人也一样。

简短的回答是否定的。每个直接检查的对象必须单独插入。 extends 关键字可用于验证对象是否具有正确的父对象(请参阅此问题 )。