Springboot配合easy-rules简单使⽤:案例1--购物实现规则
1、⼀个⼈去买酒
2、如果年龄⼤于18岁,则是成年⼈;⼩于18岁是未成年⼈
3、如果未成年⼈去买酒,拒绝
步骤⼀:导⼊依赖
<dependency>
<groupId>org.jeasy</groupId>
<artifactId>easy-rules-core</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>org.jeasy</groupId>
<artifactId>easy-rules-mvel</artifactId>
<version>3.4.0</version>
</dependency>
创建实体类
steasyrule.domain;
import org.springframework.stereotype.Component;
@Component
public class Person {
private String name;
private int age;
private boolean adult;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isAdult() {
return adult;
}
public void setAdult(boolean adult) {
this.adult = adult;
}
}
编写⼀个Rule相关的配置类,⽅便等会通过@Autowired引⽤
fig;
import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rules;
import org.jeasy.rules.api.RulesEngine;
import org.DefaultRulesEngine;
import t.annotation.Bean;
import t.annotation.Configuration;
@Configuration
public class RuleBean {
@Bean
public Facts getFacts() {
Facts facts = new Facts();
return facts;
}
@Bean
public Rules getRules() {
Rules rules = new Rules();
return rules;
}
@Bean
public RulesEngine getRulesEngine() {
RulesEngine rulesEngine = new DefaultRulesEngine();
return rulesEngine;
}
}
创建规则引擎并触发
ller;
steasyrule.domain.Person;
import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rule;
import org.jeasy.rules.api.Rules;
import org.jeasy.rules.api.RulesEngine;
import org.jeasy.rules.mvel.MVELRule;
springframework依赖import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class TestRule {
@Autowired
Person person;
@Autowired
Facts facts;
@Autowired
Rules rules;
@Autowired
RulesEngine rulesEngine;
@RequestMapping("/shop")
@ResponseBody
public void shop() {
//        创建⼀个实例
person.setName("Liu");
person.setAge(14);
Facts facts = new Facts();
facts.put("person", person);
//创建规则⼀
Rule ageRule = new MVELRule().name("年龄规则")
.description("如果⼀个⼈的年龄⼤于18岁就是成年⼈")
.
priority(1)
.when("Age() > 18")
.then("person.setAdult(true)");
//创建规则⼆
Rule alcoholRule = new MVELRule().name("酒规则")
.description("⼩孩不允许买酒")
.priority(2)
.when("person.isAdult()==false")
.then("System.out.println(\"商家:  ⼩屁孩,你在想屁吃\")");
//创建⼀个规则集
System.out.println("哟哟哟,给我来点酒");        //创建默认规则引擎并根据已知事实触发规则        rulesEngine.fire(rules, facts);
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。