當(dāng)多個規(guī)則文件的代碼相同,但是需要根據(jù)不同的參數(shù),輸出不同的結(jié)果時可以選擇使用規(guī)則模板,避免了寫多個相似的drl文件。
1.maven依賴
<!-- 模板 -->
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-templates</artifactId>
</dependency>
2.定義模板文件Cheese.drt
template header
age
type
log
package org.drools.examples.templates;
global java.util.List list;
template "cheesefans"
rule "Cheese fans_@{row.rowNumber}"
when
Person(age == @{age})
Cheese(type == "@{type}")
then
list.add("@{log}");
end
end template
3.創(chuàng)建ExampleCheese.xls

4.kmodule.xml使用模板及數(shù)據(jù)表
<kbase name="TemplatesKB" packages="org.drools.examples.templates">
<ruleTemplate dtable="org/drools/examples/templates/ExampleCheese.xls"
template="org/drools/examples/templates/Cheese.drt"
row="2" col="2"/>
<ksession name="TemplatesKS"/>
</kbase>
5.使用
KieContainer kc = KieServices.Factory.get().getKieClasspathContainer();
KieSession ksession = kc.newKieSession("TemplatesKS");
ksession.insert(new Cheese("stilton", 42));
ksession.insert(new Person("michael", "stilton", 42));
final List<String> list = new ArrayList<String>();
ksession.setGlobal("list", list);
ksession.fireAllRules();
System.out.println(list);
ksession.dispose();
參考: