javadroolskie

Drool Global Variable Initialization in drl file


 package com.example.drools; 

 global Integer count; // I want to initialize this count variable with some 
                         default value. 

   rule "Initialize"
   when
   then
       count= 1; // Locally it's possible but want it to set globally which can 
                     be use in any other rules just simply by calling it.
       System.out.println("count="+count);
   end

  rule "Drools Introduction"
  when
  then
     System.out.println("count="+count); // Here output is coming null which in 
                                            want some default value set for 
                                            global value.
  end

So Want to Initialize Count variable in drl file only ?


Solution

  • The way you update a global from inside a rule is by using the automagic variable kcontext:

    global Integer count;
    
    rule "Initialize"
    salience 100
    when
    then
           kcontext.getKieRuntime().setGlobal("count", 1);
    end    
    

    Some notes:

    Hope it helps,