How to Build a Drools 5 HelloWorld Rule Engine with Maven
This tutorial walks through Drools 5's core APIs, sets up a Maven‑managed Java project, creates a product class, writes a simple discount rule in a .drl file, and demonstrates execution with both stateful and stateless sessions, highlighting each API's role.
Drools 5 Overview
Drools implements its functionality through rule compilation, collection, and execution. The main APIs provided by Drools 5 are:
KnowledgeBuilder
KnowledgeBase
KnowledgePackage
StatefulKnowledgeSession
StatelessKnowledgeSession
These APIs handle rule file collection, compilation, error checking, fact insertion, global variable setting, and rule or rule‑flow execution.
HelloWorld Example
Business Scenario
Two products—Diamond and Gold—require separate discount calculations. Using Drools allows the discount logic to change without modifying Java code, which is useful for complex business variations.
Project Structure
The Maven‑managed Java project follows the standard layout shown below.
Maven pom.xml
The pom.xml includes dependencies for Drools 7 (which retains the Drools 5 APIs) and configures the build.
Product Class
Rules.drl File
Test Class (Drools5Test)
Execution Result
The discount for the product 1 is 25%API Details
KnowledgeBuilder : Collects written rules, compiles them into a set of KnowledgePackage objects, and provides hasErrors() and getErrors() for error handling. Supports .drl, .dslr, and .xls files.
KnowledgePackage : Holds the compiled rule objects.
KnowledgeBase : Aggregates KnowledgePackage instances; can contain ordinary rules, rule flows, functions, and type models, and creates session objects.
StatefulKnowledgeSession : Accepts external fact objects (POJOs), triggers rule execution via fireAllRules(), and requires dispose() after use to free memory.
StatelessKnowledgeSession : A lightweight wrapper around the stateful session; does not require dispose() and can insert facts only once.
Drools 7 has deprecated these APIs, but the example remains valid for understanding Drools 5 concepts.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Senior Brother's Insights
A public account focused on workplace, career growth, team management, and self-improvement. The author is the writer of books including 'SpringBoot Technology Insider' and 'Drools 8 Rule Engine: Core Technology and Practice'.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
