前边有简单使用spring boot + mvel + json 模版的格式,以下是集成spring spel的说明
具体的代码就不贴了,主要说明使用以及一些问题
注意对于beanResolver 的支持需要4.0.0-SNAPSHOT 版本
spel rule 代码定义
Rules rules = configRules.fetchConfigRules();
SpELRule spELRule = new SpELRule();
// setting an condition to be evaluated
BeanResolver beanResolver = new SimpleBeanResovler(SpringBeanUtil.getApplicationContext());
spELRule.description("bean demo");
spELRule.priority(20);
spELRule.when("#user.age < 38");
spELRule.then("@myService.setInfo(#user)",beanResolver);
Facts facts = new Facts();
// 生成一个唯一id,方便基于数据id规则流程查询
user.setUniqueId(UUID.randomUUID().toString());
MyRule<User> rule = new MyRule<User>();
rules.register(spELRule);
ules.register(rule);
配置文件在SpELRuleFactory方式加载
package com.appdemo.demo;
import org.jeasy.rules.api.Rules;
import org.jeasy.rules.spel.SpELRuleFactory;
import org.jeasy.rules.support.JsonRuleDefinitionReader;
import org.jeasy.rules.support.RuleDefinitionReader;
import org.springframework.expression.BeanResolver;
import org.springframework.expression.ParserContext;
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.stereotype.Component;
import java.io.FileReader;
/**
* @author dalong
* 加载rule文件
*/
@Component
public class ConfigRules {
public Rules fetchConfigRules() throws Exception {
BeanResolver beanResolver = new SimpleBeanResovler(SpringBeanUtil.getApplicationContext());
// 注意beanResolver的传递
SpELRuleFactory ruleFactory = new SpELRuleFactory(new JsonRuleDefinitionReader(),beanResolver);
Rules jsonRules = ruleFactory.createRules(new FileReader(DemoApplication.class.getClassLoader().getResource("rules-json.json").getFile()));
return jsonRules;
}
}
一个参考spel json 配置文件
[{
"name": "1",
"description": "1",
"priority": 1,
"compositeRuleType": "UnitRuleGroup",
"composingRules": [
{
"name": "2",
"description": "2",
"condition": "#{#user.age >= 18}",
"priority": 2,
"actions": [
"#{@myService.setInfo(#user)}",
"#{T(com.appdemo.demo.UserService).doAction4(#user)}"
]
}
]}
]
简单说明
因为spel 支持使用spring bean,但是因为目前SpELRuleFactory 在处理spel 以及对于beanResolver参数传递上beanResolver
不能共享,造成对于SpELRule rule 的定义需要自己配置beanResolver,如果真的需要使用spel,推荐还是使用java 代码方
式(这样可以更好的利用spring的特性)
参考资料
https://github.com/j-easy/easy-rules/wiki/expression-language-support
https://github.com/j-easy/easy-rules/wiki/getting-started
https://github.com/rongfengliang/easy-rules-spring-learning/tree/spel
来源:oschina
链接:https://my.oschina.net/u/4255780/blog/3235079