Passing parameters in drools

ir2pid picture ir2pid · May 1, 2014 · Viewed 10.1k times · Source

How can I pass a parameter to set the comparing value of age(18 should be dynamic) in the below drools rule

package com.rule.models

import com.rule.models.User

rule "AgeCheck"
when
    $user: User( age < 18 )
then
    System.out.println("Warning, "+$user.getName()+" is below age!");
end

Answer

laune picture laune · May 1, 2014

For rules in Drools, there is nothing comparable to "parameter passing". Data used in rules must come from facts in Working Memory or from global variables.

Using the first technique would look like this:

rule "AgeCheck"
when
    Parameter( $ageLimit: ageLimit )
    $user: User( age < $ageLimit )
then ... end

A single fact of class Parameter must be inserted initially; it may contain more than one parameter.

Using a global variable is also possible:

global my.app.Parameter parameter

rule "AgeCheck"
when
    $user: User( age < parameter.getAgeLimit() )
then ... end

See the Expert manual for details about how to install a global.