我如何通过编程方式生成 .drl 文件。任何示例都会对我有所帮助

how can i generate .drl file through programmatically .Any example would be helpful for me

我搜索了很多网站,但找不到任何关于 .drl 文件生成的具体相关示例。关于 .drl 文件生成的文档也不值得。

最近版本的 Drools 开始以一种使用流利的 API 以编程方式定义规则的方式工作。我自己在一些内部项目中使用了这个 API,它足够灵活,可以满足我的需要。 API 的缺点是:

  • 没有记录(您可以找到 some tests in the code,差不多就是这样)。
  • 它被认为是内部 API,因此它可以在没有向后兼容性的情况下在未来改变。
  • 有时,API 还不够 "typed"。约束的某些部分必须指定为字符串块。

但是您可能需要考虑一个可能更好的替代方案。 DRL 只不过是一个文本文件。如果您想根据某些数据以编程方式生成一些规则,您可以使用 String Template or Velocity 等模板框架来即时创建 DRL。

希望对您有所帮助,

// -------package section-------
PackageDescr pkg=new PackageDescr();
pkg.setName("com.demo.model");

// -------import section here-------
ImportDescr importEntry1= new ImportDescr();
importEntry1.setTarget("com.demo.model.Purchase");
pkg.addImport(importEntry1);
ImportDescr importEntry2= new ImportDescr();
importEntry2.setTarget("com.demo.model.PotentialCustomer");
pkg.addImport(importEntry2);

ImportDescr importEntry3= new ImportDescr();
importEntry3.setTarget("com.demo.model.PaymentMethod");
pkg.addImport(importEntry3);

//-------global section here-------
GlobalDescr globalEntry=new GlobalDescr();
globalEntry.setType("org.slf4j.Logger");
globalEntry.setIdentifier("logger");
pkg.addGlobal(globalEntry);

//------- rule section here
RuleDescr ruleEntry=new RuleDescr();
ruleEntry.setName("Identify potential customers");

// ------- lhs starts here ------- 
AndDescr lhs=new AndDescr();

//-------  pattern starts here ------- 
PatternDescr patternEntry1=new PatternDescr();
patternEntry1.setIdentifier("$p");
patternEntry1.setObjectType("Purchase");

//------- ExprConstraint starts here ------- 
 ExprConstraintDescr ecd1=new ExprConstraintDescr();
 ecd1.setExpression("paymentMethod");
 ExprConstraintDescr ecd2=new ExprConstraintDescr();
 ecd2.setExpression("PaymentMethod.CASH");
//-------  Added exprConstraint into relational expr------- 
    RelationalExprDescr red1=new RelationalExprDescr("==",false, null, ecd1, ecd2);

    ExprConstraintDescr ecd3=new ExprConstraintDescr();
    ecd3.setExpression("subTotal");
    ExprConstraintDescr ecd4=new ExprConstraintDescr();
    ecd4.setExpression("300");
    RelationalExprDescr red2=new RelationalExprDescr(">",false, null, ecd3, ecd4);


patternEntry1.addConstraint(red1);
patternEntry1.addConstraint(red2);
lhs.addDescr(patternEntry1);

NotDescr notDescr=new NotDescr();
notDescr.setText("not");


PatternDescr pattDescr1=new PatternDescr();
pattDescr1.setObjectType("PotentialCustomer");

ExprConstraintDescr ecd11=new ExprConstraintDescr();
ecd11.setExpression("customerName");
ExprConstraintDescr ecd12=new ExprConstraintDescr();
ecd12.setExpression("$p.getCustomerName()");
RelationalExprDescr red11=new RelationalExprDescr("==",false, null, ecd11,ecd12);
pattDescr1.addConstraint(red11);
notDescr.addDescr(pattDescr1);
lhs.addDescr(notDescr);


ruleEntry.setLhs(lhs);

pkg.addRule(ruleEntry);
String drl = new DrlDumper().dump( pkg );

 // here drl is in form of String