Skip to content

expression language support

Mahmoud Ben Hassine edited this page Apr 20, 2018 · 14 revisions

As of version 3.1, Easy Rules provides support for defining rules with MVEL. Support for other Expression Language libraries (Spring Expression Language (SpEL), JbossEL, etc) will be added in future releases.

MVEL support is provided through the easy-rules-mvel module. This module provides APIs to define conditions, actions and rules.

Define rules in a programmatic way

Conditions, actions and rules are represented respectively by the MVELCondition, MVELAction and MVELRule classes. You can define your rule with a fluent API as follows:

Rule ageRule = new MVELRule()
        .name("age rule")
        .description("Check if person's age is > 18 and marks the person as adult")
        .priority(1)
        .when("person.age > 18")
        .then("person.setAdult(true);");

Create rules from a rule descriptor

You can also define a rule in a descriptor file and use the MVELRuleFactory to create a rule from the descriptor. Here is an example alcohol-rule.yml:

name: "alcohol rule"
description: "children are not allowed to buy alcohol"
priority: 2
condition: "person.isAdult() == false"
actions:
  - "System.out.println(\"Shop: Sorry, you are not allowed to buy alcohol\");"
MVELRule alcoholRule = MVELRuleFactory.createRuleFrom(new FileReader("alcohol-rule.yml"));

You can find a complete example of how to use Easy Rules with MVEL in the shop tutorial.

You can also create multiple rules at the same time from a single file. For instance, here is a rules.yml file:

---
name: adult rule
description: when age is greater then 18, then mark as adult
priority: 1
condition: "person.age > 18"
actions:
  - "person.setAdult(true);"
---
name: weather rule
description: when it rains, then take an umbrella
priority: 2
condition: "rain == true"
actions:
  - "System.out.println(\"It rains, take an umbrella!\");"

To load these rules into a Rules object, you can use the following snippet:

Rules rules = MVELRuleFactory.createRulesFrom(new FileReader("rules.yml"));