Drools global variable - Java @ Desk

Monday, July 1, 2013

Drools global variable

What is global in DRL file?

global is the keyword used in drools to define a global variable. Global variable is the one which will be visible to all the rules inside a DRL file.
Globals must be used very carefully in a DRL file, since the changes in a global variable are not notified to the working memory. For example, you are using a list variable as a global and in any rule you are adding a value in a list and in one particular rule, you are checking if list size() > 0, then in this case rule may not fire. Global variable can be used for any type of object.

Where to use global variable?

Consider a scenario, where in the rules there is a requirement for database connection object. In this case, the DB Connection object can be inserted as a global variable in the working memory and the connection object will be visible to all the rules in that DRL file.

GlobalDrl.drl

global java.util.List globalList;

rule "Global implementation"
when
    eval( true )
then
    globalList.add( "Hello World" );
end

Java client file

List list = new ArrayList();

KnowledgeSession knowledgeSession = knowledgeBase.newStatefulSession();

knowledgeSession.setGlobal( "globalList", list );

It is strongly discouraged to set or change a global value from inside your rules. We recommend to you always set the value from your application using the working memory interface.






No comments:

Post a Comment