springboot easyrules详细demo
时间: 2023-06-13 13:08:06 浏览: 204
好的,下面是一个简单的 Spring Boot + EasyRules 的示例:
首先,需要在 pom.xml 中添加以下依赖:
```xml
<dependency>
<groupId>org.jeasy</groupId>
<artifactId>easy-rules-spring-boot-starter</artifactId>
<version>3.6.0</version>
</dependency>
```
然后,创建一个规则类:
```java
import org.jeasy.rules.annotation.Action;
import org.jeasy.rules.annotation.Condition;
import org.jeasy.rules.annotation.Rule;
@Rule(name = "adult rule", description = "Check if person is an adult", priority = 1)
public class AdultRule {
@Condition
public boolean isAdult(@Fact("age") int age) {
return age >= 18;
}
@Action
public void printAdultMessage(@Fact("person") String person) {
System.out.println(person + " is an adult");
}
}
```
在这个规则类中,我们定义了一个名为 AdultRule 的规则,它会检查一个人的年龄是否大于等于 18 岁。如果是,就会执行 printAdultMessage 方法,打印出这个人是成年人的信息。
接下来,我们需要在 Spring Boot 中配置这个规则:
```java
import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rules;
import org.jeasy.rules.mvel.MVELRuleFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RuleConfig {
@Bean
public Rules rules() throws Exception {
MVELRuleFactory ruleFactory = new MVELRuleFactory(new YamlRuleDefinitionReader());
Rules rules = ruleFactory.createRules(getClass().getResourceAsStream("/rules.yml"));
return rules;
}
@Bean
public Facts facts() {
Facts facts = new Facts();
facts.put("age", 20);
facts.put("person", "John");
return facts;
}
}
```
在这个配置类中,我们使用了 EasyRules 提供的 MVELRuleFactory 和 YamlRuleDefinitionReader 类,将规则定义文件(/rules.yml)解析成 EasyRules 的规则集合。我们还定义了一个 Facts 对象,它包含了我们要检查的人的年龄和姓名。
最后,我们可以在一个 Spring Boot 的 Controller 中使用这个规则:
```java
import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rules;
import org.jeasy.rules.core.RulesEngine;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RuleController {
private final RulesEngine rulesEngine;
private final Rules rules;
private final Facts facts;
public RuleController(RulesEngine rulesEngine, Rules rules, Facts facts) {
this.rulesEngine = rulesEngine;
this.rules = rules;
this.facts = facts;
}
@GetMapping("/checkAge")
public String checkAge() {
rulesEngine.fire(rules, facts);
return "Done";
}
}
```
在这个 Controller 中,我们注入了 RulesEngine、Rules 和 Facts 对象,并在 checkAge 方法中调用了 rulesEngine.fire 方法,触发规则的执行。
最后,我们需要在 resources 目录下创建一个名为 rules.yml 的规则定义文件:
```yaml
rules:
- name: "adult rule"
description: "Check if person is an adult"
priority: 1
condition: "age >= 18"
actions:
- "System.out.println(person + \" is an adult\")"
```
这个文件中定义了一个名为 adult rule 的规则,它的条件是年龄大于等于 18,执行的操作是打印出这个人是成年人的信息。
这就是一个基于 Spring Boot 和 EasyRules 的示例,它演示了如何定义规则、配置规则和在应用程序中使用规则。
阅读全文
相关推荐













