eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Introduction

In many Drools-based applications, it’s important not only to execute rules but also to understand which rules actually fired. In this article, we explore multiple approaches to track fired rules in Drools, including a custom AgendaEventListener and a RuleContext-based utility method.

2. Maven Dependency

KIE (Knowledge Is Everything) is the core framework behind Drools. It provides the infrastructure for defining and executing business rules and other knowledge assets outside of application code. Let’s start by importing the kie-ci dependency to our pom.xml:

<dependency>
    <groupId>org.kie</groupId>
    <artifactId>kie-ci</artifactId>
    <version>10.0.1</version>
</dependency>

The kie-ci is required when using Maven-based KIE modules and dynamic rule loading, which is a common pattern in modern Drools setups.

3. Drools Example

In this section, we’ll walk through a simple example that demonstrates how to use Drools in practice.

3.1. The Person Model

To demonstrate how rule tracking works, we start with a simple Person domain model:

public class Person {
    private String name;
    private int age;
    private boolean eligibleToVote;
    private boolean priorityVoter;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
        this.eligibleToVote = false;
        this.priorityVoter = false;
    }

    // standard getters and setters
}

This class defines a few attributes relevant to voting decisions, such as a person’s age and voter-status flags. The rules will update these fields as the conditions are evaluated.

3.2. The Rule File

Next, we define our rules inside a DRL file:


rule "Check Voting Eligibility Event"
    when
        $person : Person(age >= 18)
    then
        $person.setEligibleToVote(true);
        update($person);
end

rule "Senior Priority Voting Event"
    when
        $person : Person(age >= 65)
    then
        $person.setPriorityVoter(true);
        update($person);
end

Each rule evaluates a specific condition on the Person object and updates the appropriate fields:

  • Check Voting Eligibility – Marks a person as eligible to vote if they meet the minimum age requirement.
  • Senior Priority Voting – Assigns priority voting status to individuals who fall within the senior age group.

4. Find List of Matched Rules Using AgendaEventListener

In this section, we introduce a custom AgendaEventListener that automatically records each fired rule.

4.1. AgendaEventListener

Drools provides several built-in event listeners that allow us to react to different phases of the rule engine lifecycle. To track which rules were actually fired during a session, we can register an AgendaEventListener and listen specifically for the afterMatchFired() event. This callback is invoked immediately after a rule is successfully executed. Let’s create the TrackingAgendaEventListener class:

public class TrackingAgendaEventListener extends DefaultAgendaEventListener {
    private final List<Match> matchList = new ArrayList<>();

    @Override
    public void afterMatchFired(AfterMatchFiredEvent event) {
        matchList.add(event.getMatch());
    }

    public List<String> getFiredRuleNames() {
        List<String> names = new ArrayList<>();
        for (Match m : matchList) {
            names.add(m.getRule().getName());
        }
        return names;
    }

}

Here, the listener overrides only the afterMatchFired() method, which is sufficient for logging rule execution. Every time a rule fires, the listener extracts the rule’s name from the event and appends it to the tracker. Now, we need to attach the listener to the KieSession:

KieSession kieSession = new DroolsBeanFactory().getKieSession();

TrackingAgendaEventListener listener = new TrackingAgendaEventListener();
kieSession.addEventListener(listener);

This approach is completely decoupled from the DRL file—no modifications to the rules themselves are required—making it a clean and non-intrusive way to audit rule execution.

4.2. Test

Let’s create a test to verify that our TrackingAgendaEventListener correctly records the names of the rules that fire during the execution of the Drools session:

@Test
public void givenRuleFired_whenListenerAttached_thenRuleIsTracked() {

    // Given
    Person person = new Person("Bob", 65);

    TrackingAgendaEventListener listener = new TrackingAgendaEventListener();
    kieSession.addEventListener(listener);

    // When
    kieSession.insert(person);
    kieSession.fireAllRules();
    kieSession.dispose();

    // Then
    assertFalse(listener.getFiredRuleNames().isEmpty());
    assertTrue(listener.getFiredRuleNames().contains("Check Voting Eligibility Event"));
    assertTrue(listener.getFiredRuleNames().contains("Senior Priority Voting Event"));
}

We begin by creating a Person instance whose attributes satisfy the conditions of both rules in our rule set. In this example, a 65-year-old person triggers both the “Check Voting Eligibility Event” rule (because age ≥ 18) and the “Senior Priority Voting Event” rule (because age ≥ 65). Next, we register our custom TrackingAgendaEventListener with the KieSession. By attaching the listener before inserting the facts, we ensure that every rule fired during the session is captured. After inserting the Person fact and executing the rules, we inspect the listener to confirm the results.

5. Find List of Matched Rules Using RuleContext

In this section, we introduce a RuleContext-based method that allows manual tracking within the DRL file.

5.1. RuleContext

While an AgendaEventListener provides a non-intrusive way to observe rule execution from outside the rule base, in some cases, we may want finer control over when and how a rule is recorded. Drools exposes this capability through the RuleContext API, which provides access to the rule currently being executed from within the DRL file itself. To use this approach, we define a small utility class containing a static method that accepts both the rule context and our RuleTracker:

public class RuleUtils {

    public static void track(RuleContext ctx, RuleTracker tracker) {
        String ruleName = ctx.getRule().getName();
        tracker.add(ruleName);
    }
}

This method extracts the active rule’s name from the Drools context and appends it to the tracker. Let’s create the RuleTracker class:

public class RuleTracker {

    private final List<String> firedRules = new ArrayList<>();

    public void add(String ruleName) {
        firedRules.add(ruleName);
    }

    public List<String> getFiredRules() {
        return firedRules;
    }
}

Unlike the listener-based approach, this mechanism allows the rule author to decide exactly where rule tracking should occur within the consequence block. To make the method available inside the .drl file, we import it at the top of the rule file and invoke the method directly inside a rule:

package com.baeldung.drools.rules

import com.baeldung.drools.matched_rules.Person;
import com.baeldung.drools.matched_rules.RuleTracker;
import static com.baeldung.drools.matched_rules.RuleUtils.track;

rule "Check Voting Eligibility"
    when
        $person : Person(age >= 18)
        $tracker : RuleTracker()
    then
        track(drools, $tracker);
        $person.setEligibleToVote(true);
        update($person);
end

rule "Senior Priority Voting"
    when
        $person : Person(age >= 65)
        $tracker : RuleTracker()
    then
        track(drools, $tracker);
        $person.setPriorityVoter(true);
        update($person);
end

5.2. Test

Let’s create a unit test to verify that when a Person instance satisfies the conditions of our rules, the RuleContext-based tracking correctly records all fired rules:

@Test
public void givenPerson_whenRulesFire_thenContextTracksFiredRules() {

    // Given
    Person person = new Person("John", 70);
    RuleTracker tracker = new RuleTracker();

    // When
    kieSession.insert(person);
    kieSession.insert(tracker);

    kieSession.fireAllRules();
    kieSession.dispose();

    // Then
    List<String> fired = tracker.getFiredRules();

    assertTrue(fired.contains("Check Voting Eligibility"));
    assertTrue(fired.contains("Senior Priority Voting"));

    assertTrue(person.isEligibleToVote());
    assertTrue(person.isPriorityVoter());
}

We create a Person aged 70, who satisfies both rules (Check Voting Eligibility and Senior Priority Voting), and a RuleTracker to capture fired rules. Then, we insert both facts into the KieSession, and call fireAllRules(), which executes the rules. Finally, we assert that both expected rules are present in the RuleTracker and the Person instance has the correct fields updated (eligibleToVote and priorityVoter).

6. Conclusion

In this article, we explored two practical techniques for determining which Drools rules were fired during a KIE session. Using an AgendaEventListener allows us to track rule executions transparently without modifying the rule files, making it a clean, non-intrusive option for most applications. On the other hand, the RuleContext approach offers explicit, rule-level control by recording rule firings directly within the DRL itself. As always, the source code is available over on GitHub.

Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)