Search code examples
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:

    • You should use a high salience in your rule so it gets executed before any other rule that is also using the global.
    • This method will not work if you are using the global in the LHS of your rules. If that's the case I would suggest to use a Fact instead of a global.

    Hope it helps,