urule开源版自定义动作库注意事项
urule开源版自定义动作库注意事项
动作库文件的作用是对配置在spring中的bean方法进行映射,使得我们可以直接在规则当中调用这些方法。同样在项目的“库”节点下创建一个动作库文件,可以看到动作库文件内容有三列,分别是动作名称,bean的id定义列,方法名定义列,以及方法对应的参数定义列,如下图所示:
测试类如下:
/** Unpublished work.* Copyright (c) 2016 by RDS Corporation. All rights reserved.* RDS CORPORATION CONFIDENTIAL AND TRADE SECRET*/
package com.rds.szrcb.web.util;import java.lang.reflect.Member;
import java.text.SimpleDateFormat;
import java.util.Date;import com.bstek.urule.action.ActionId;
import com.bstek.urule.model.ExposeAction;public class MethodTest {@ActionId("helloKey")public String hello(String username){System.out.println("hello "+username);return "hello"+username;}@ExposeAction("方法1")public boolean evalTest(String username){if(username==null){return false;}else if(username.equals("张三")){return true;}return false;}@ExposeAction("测试Int")public int testInt(int a,int b){return a+b;}public int testInteger(Integer a,int b){return a+b*10;}@ExposeAction("打印内容")public void printContent(String username,Date birthday){SimpleDateFormat sd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");if(birthday!=null){System.out.println(username+"今年已经"+sd.format(birthday)+"岁了!"); }else{System.out.println("Hello "+username+"");}}@ExposeAction("打印Member")public void printUser(Member m){System.out.println("Hello "+", has house:");}
}
在这个MethodTest类中,我们对需要在动作库中引用的方法上都添加了一个名为ExposeAction的annotation,这就表示这个方法可以暴露给规则引用,反之如果不加这个annotation,那么这个方法就不能在规则中引用。同样我们也看到对于需要在动作库中引用的方法是不需要实现任何接口的,方法签名也是任意的,只需要在方法上添加ExposeAction这个annotation即可,接下来,我们需要将这个类配置到spring中,让其成为一个标准的bean,spring中的配置如下:
<bean id="methodTest" class="com.rds.szrcb.web.util.MethodTest"/>
在这其中,有一些需要注意的:
- 要在方法上添加@ExposeAction("")注解。
- 定义动作库的Bean时,一定不要忘记给Bean定义一个Id,这样才能保证规则在任何地方运行都不会出错,这点很关键。(规则引擎页面可以通过这个Id映射到动作类,不然会报这个Bean名称未被定义)。
- 注解@ExposeAction("")所在的方法必须是public的,不能是private,不然在页面不会映射出来。
- 注解@ExposeAction("")不能定义在构造方法上。
- 如果这个类里有了有参构造方法,那么必须定义一个无参构造,否则会报BeanCreationException异常。
- 如果是Spring Boot类项目,则只需要在启动类添加@ImportResource({"classpath:urule-console-context.xml"}),然后直接使用注解@ExposeAction(""),不需要定义Bean Id。默认是类全名,首字母小写。
下图中的Bean Id 是在spring中定义的bean id。输入正确的Bean Id 和动作名称(可随意)后,点击操作列的“手指”即可映射出定义的方法。
映射出来的方法:
最后,虽然在web层或者controller层定义的方法可以不在spring中定义Bean,(Bean Id)默认是类全名,首字母小写。但页面会报错,实际上也可以映射出自定义动作库的方法。但不建议这么做。如下图:
顺便提一下注解的源码:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExposeAction {public String value();
}