Spring Boot + JBoss Drools Hello World Example | CodeUsingJava






















Spring Boot + JBoss Drools Hello World Example


What is a Rules Engine?

A rules engine can be described as a domain expert system which applies the business rules on the given input data and if the rule condition is satisfied then the corresponding action gets executed.

Rules Engine

Video Tutorial

Consider an example where we are designing an interest calculation system for a bank.
Rules Engine For Bank
In bank there will be business analyst who will be studying various factors like bank interest rates, applicant age, type of deposit i.e whether fixed or recurring, deposit duration etc. and accordingly the interest rate will be calculated. If the above logic is implemented in java it will have following disadvantages -
  • Java is an imperative language. A set of instructions are written that the program executes. So there will be multiple if else loops that will need to be written. Any change like duration rule will need to be changed in the code. This may involve adding more if else loops.
  • Tight coupling between Business Rules and code/data
  • Not much readable for non technical people like domain experts

What is Jboss Drools?

Drools is a Business Rules Management System (BRMS) solution. Using this framework users define rules that specify what action needs to be done when a particular condition is met. It extends and implements the Rete Pattern matching algorithm. In projects its usually used to define Business Rules. Business rules are composed of facts and conditional statements.

Drools Rules Engine For Bank
Advantages of using Jboss Drools -
  • Drools is declarative language. What ever task is to be achieved is described in small steps
  • The rules are written seperately in drl file. So no tight coupling between Business Rules and code/data
  • Very much readable for non technical people like domain experts

Implementation


Spring Boot + Drools Hello World Example
Go to Spring Initializr website and select the following dependencies -
  • Web
The maven project we will be creating is as follows -
Spring Boot + Drools Maven
Next we will be adding the drools dependencies in the pom.xml. So the pom.xml is as follows -
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.4.2</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.codeusingjava</groupId>
	<artifactId>boot-drools</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>boot-drools</name>
	<description>Demo project for Drools Spring Boot</description>
	<properties>
		<java.version>1.8</java.version>
		<drools.version>7.49.0.Final</drools.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.drools</groupId>
			<artifactId>drools-core</artifactId>
			<version>${drools.version}</version>
		</dependency>
		<dependency>
			<groupId>org.drools</groupId>
			<artifactId>drools-compiler</artifactId>
			<version>${drools.version}</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>
Define the domain class as follows -
package com.codeusingjava.domain;

public class DepositRequest {
	private String loanType;
	private Integer durationInYear;
	private Integer age;
	private String interestRate;

	public DepositRequest(String loanType, Integer durationInYear, Integer age) {
		super();
		this.loanType = loanType;
		this.durationInYear = durationInYear;
		this.age = age;
	}

	public String getLoanType() {
		return loanType;
	}

	public void setLoanType(String loanType) {
		this.loanType = loanType;
	}

	public Integer getDurationInYear() {
		return durationInYear;
	}

	public void setDurationInYear(Integer durationInYear) {
		this.durationInYear = durationInYear;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public String getInterestRate() {
		return interestRate;
	}

	public void setInterestRate(String interestRate) {
		this.interestRate = interestRate;
	}

}
	
Next we will be defining the drools rules file as follows. In this file we check the values of loan type, age and loan duration to determine the interest rate. It makes use of the MVEL syntax.
Spring Boot + Drools Rules
import  com.codeusingjava.domain.DepositRequest;

rule "Interest Rate for Fixed deposit duration between 1 year and 2 years and age less than 60 years"
    when
        depositObject : DepositRequest( loanType=="Fixed" && durationInYear >= 1 && durationInYear < 2 && age < 60);
    then
        depositObject.setInterestRate("5%");
end;

rule "Interest Rate for Recurring deposit duration between 1 year and 2 years and age less than 60 years"
    when
        depositObject : DepositRequest( loanType=="Recurring" && durationInYear >= 1 && durationInYear < 2 && age < 60);
    then
        depositObject.setInterestRate("3%");
end;
Define the Drools configuration file as follows. We initialize the KieFileSystem bean which is in-memory file system provided by the framework. We load the rules we have defined in the drl file and then using the KieContainer execute these rules againt an object
package com.codeusingjava.config;

import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieModule;
import org.kie.api.runtime.KieContainer;
import org.kie.internal.io.ResourceFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DroolsConfiguration {

	private final KieServices kieServices = KieServices.Factory.get();

	@Bean
	public KieContainer kieContainer() {
		KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
		kieFileSystem.write(ResourceFactory.newClassPathResource("depositInterestRate.drl"));
		KieBuilder kb = kieServices.newKieBuilder(kieFileSystem);
		kb.buildAll();
		KieModule kieModule = kb.getKieModule();
		return kieServices.newKieContainer(kieModule.getReleaseId());
	}
}
Define the controller class as follows. In this class we autowire kieContainer that we created in the configuration class. Using this bean initiate a kieSession and evaluate our rules
package com.codeusingjava.controller;

import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.codeusingjava.domain.DepositRequest;

@RestController
public class DepositRateController {

	@Autowired
	private KieContainer kieContainer;

	@RequestMapping(value = "/getInterestRate", method = RequestMethod.GET, produces = "application/json")
	public String getInterest(@RequestParam(required = true) String loanType,
			@RequestParam(required = true) Integer durationInYear, @RequestParam(required = true) Integer age) {
		KieSession kieSession = kieContainer.newKieSession();
		DepositRequest depositRequest = new DepositRequest(loanType, durationInYear, age);
		kieSession.insert(depositRequest);
		kieSession.fireAllRules();
		kieSession.dispose();
		return "The interest rate for this application is " + depositRequest.getInterestRate();
	}
}
Finally define the Spring Boot Bootstrap class as follows-
package com.codeusingjava;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DroolsDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DroolsDemoApplication.class, args);
	}
}
Start the application. If we now hit the url - http://localhost:8080/getInterestRate?loanType=Fixed&age=55&durationInYear=1
Spring Boot + Drools Output

Download the code of origin-

Download Spring Boot + Drools Example Code-
Spring Boot + Drools Example