java - Easy-rules:使用构造函数在 POJO 中设置规则名称

标签 java easy-rules

我有以下规则

@Rule
@Slf4j
public class ModuleRule{

  private Content content;
  private String baseDir;


  @Condition
  public boolean when(Facts facts) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    content = facts.get("content");
    baseDir = facts.get("base_dir");

    Method getModule = content.getClass().getMethod("get"+name);
    return (boolean) getModule.invoke(content);
  }

  @Action
  public void then(@Fact("toInclude") List<Template> selectedTemplates) throws IOException, TemplateGenUtilsException {
    log.info("Adding module:" + name);
    final String moduleTemplatesPath = String.format("%s/%s", baseDir, name);
    selectedTemplates.addAll(FileUtils.replacePath(moduleTemplatesPath, FileUtils.loadTemplates(name), content.getDOMAIN(), content.getAPP_NAME()));
  }
}

通过以下方式实例化:

 @Bean
  public Rules rules() {
    Rules rules = new Rules();

    templatesConfig.getModules().stream() .   //Modules is a list of String
        .map(ModuleRule::new)
        .forEach(rules::register);

    return rules;
  }

该代码在第一次注册后将不起作用,其他规则具有相同的名称,因此不会被注册。 因此,这是我的问题:有没有办法创建新规则并在运行时设置其名称?

我还尝试扩展BasicRules,这里的问题是当引擎启动时,规则不会被评估。这是代码:

@Slf4j
public class ModuleRule extends BasicRule{


  private Content content;
  private String templatesBaseDir;


  public ModuleRule(String name) {
    super(name);
  }

  @Condition
  public boolean when(Facts facts) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    content = facts.get("content");
    templatesBaseDir = facts.get("base_dir");

    Method getModule = content.getClass().getMethod("get"+name);
    return (boolean) getModule.invoke(content);
  }

  @Action
  public void then(@Fact("toInclude") List<Template> selectedTemplates) throws IOException, TemplateGenUtilsException {
    log.info("Adding module:" + name);
    final String moduleTemplatesPath = String.format("%s/%s", templatesBaseDir, name);
    selectedTemplates.addAll(FileUtils.replacePath(moduleTemplatesPath, FileUtils.loadTemplates(name), content.getDOMAIN(), content.getAPP_NAME()));
  }

最佳答案

愚蠢的错误:BasicRule 扩展可以工作,但您需要重写执行和评估方法,而不是使用注释。

现在一切正常!

关于java - Easy-rules:使用构造函数在 POJO 中设置规则名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59078166/

相关文章:

java - 如何在 Java 中测试 UTF-8 字符串

java - 尝试在 macOS Catalina 上安装 Spring Tools App 4.7.0

java - 如何在 Java 中创建包含随机生成的数字的字符串列表?

java - Play 2.4.2 JavaWs 给出 null

java - 如何在 easy-rules 中编写规则,该规则接受字符串数组并使用 contains 检查事实字符串?

java - 如何定义 EasyRules 中只需要执行一条规则?

java - ArrayList 的 isEmpty() 方法出现 ConcurrentModificationException