Tag Archives: Spring

Spring Drools: Spring Business Rules sample

Drools is a decent business rules engine from JBoss. One of the powerful features of Drools Business Rules Engine is something like a excel decision table. In this blog I will demonstrate how to implement Business Rules in Excel decision table feature using Spring. The working maven based project is @ Github . For people in hurry, you can just run mvn test and you can see what is going on!

This usecase is an example in Drools example, rewritten using Spring. The Pricing Rule decision table demo’s the use of a Excel decision table, in calculating the cost of an insurance policy based on Driver’s age, location, number of prior claims and calculates the base price and the discount.

Drools Business Rules

Business Rules

Spring Dools Excel decision table as per Drools examples

Row 2 of the Decision table indicates the package where all these class that is passed to the Decision table are present.
The decision table take 2 parameters, Driver and Policy if you notice in row 7 both these are indicated. Row 8 consists of the property (getter/setters) of the above objects, for example, age is a property of the Driver. When we pass a Driver object is passed to the rule engine, it will validate each rule and check which rule the Driver object is related to and applies those policies and discount to the Driver object. Let me walk you thru the example. As always, I will start with the JUnit test as below,

public class PricingRuleDTExampleTest {

PricingRuleDTExample ruleRunner;

public void testExecuteExample() throws Exception {

Driver driver = new Driver();
Policy policy = new Policy();

assertTrue( ruleRunner.executeExample(driver, policy) == 120);
// now create some test data
ksession.execute(Arrays.asList(new Object[] { driver, policy }));

logger.debug("BASE PRICE IS: " + policy.getBasePrice());
logger.debug("DISCOUNT IS: " + policy.getDiscountPercent());

return policy.getBasePrice();

The test will fail because ksession has not been initiated using spring configuration. Spring configuration looks as below,

	<drools-spring:kbase id="kbase">
<drools-spring:resource type="DTABLE" source="classpath:rules/org/drools/examples/ExamplePolicyPricing.xls" >
<drools-spring:decisiontable-conf input-type="XLS" worksheet-name="Tables"/>

<drools-spring:ksession id="ksession" type="stateless" kbase="kbase" />

<bean id="pricingRule" class="com.goSmarter.drools.PricingRuleDTExample">
<property name="ksession" ref="ksession" />
<property name="kbase" ref="kbase" />

Now we need to go back and wire the test

@ContextConfiguration( { "classpath:price-rule-config.xml" })
public class PricingRuleDTExampleTest {

PricingRuleDTExample ruleRunner;

Your test succeed.