如何在Drools规则中使用Spring Service? [英] How to use a Spring Service in Drools rules?
问题描述
我正在使用流口水引擎来构建警报系统.当条件满足时,我们需要对规则(RHS)的操作执行由Spring Framework实例化的 @Service 方法.
I'm working with drools engine in the construction of an alert system. we need to execute a method of a @Service instantiated by Spring Framework on the actions of the rule (RHS), when the conditions are met.
如何获取由Spring Framework创建的 @service实例,以供Drools规则的操作(RHS)使用?
What would be the way to get the @service instance created by Spring Framework to be used by the action (RHS) of the Drools rule?
我已遵循以下指示:
- 使用表格导入功能( Rule1.drl ).该解决方案不起作用,因为该类是在drool中实例化的,并且需要执行静态方法.
- 使用全局会话变量( Rule2.drl ).此解决方案在运行时"抛出一个异常,表明它不是同一类类型.
- Using the form import function (Rule1.drl). This solution does not work because the class is instantiated in drools and requires static methods to be executed.
- Using a global Session variable (Rule2.drl). This solution throws me an exception at "runtime" indicating that it is not the same class type.
关于如何使用它的任何想法?
Any ideas on how to use it?
为
文件: Rule1.drl
package com.mycompany.alerts.Alert;
import function com.mycompany.alerts.service.SecurityService.notifyAlert;
rule "Activate Alert Type"
salience 9000
when
$alert: Alert(type == "TYPE1")
then
System.out.println("Running action:" + drools.getRule().getName());
$alert.setActive(Boolean.TRUE);
notifyAlert($alert.getStatus(),$alert.getSmsNumber());
System.out.println("End action:" + drools.getRule().getName());
end
文件: Rule2.drl
package com.mycompany.alerts.Alert;
global com.mycompany.alerts.service.SecurityService securityService;
rule "Activate Alert Type 2"
salience 9000
when
$alert: Alert(type == "TYPE2")
then
System.out.println("Running action:" + drools.getRule().getName());
$alert.setActive(Boolean.TRUE);
securityService.notifyAlert($alert.getStatus(),$alert.getSmsNumber());
System.out.println("End action:" + drools.getRule().getName());
end
文件: SecurityService.java
package com.mycompany.alerts.service;
import com.mycompany.alerts.service.UserRepository;
@Service
@Transactional
public class SecurityService {
private final Logger log = LoggerFactory.getLogger(SecurityService.class);
private final UserRepository userRepository;
public SecurityService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public void notifyAlert(String status, String sms) {
System.out.println("Alert notify with:" + status + " sms:" + sms);
}
}
推荐答案
您可以将kieRuntime的setGlobal函数用作:
You can use the setGlobal function of kieRuntime as:
kieRuntime.setGlobal("securityService", securityService);
然后,您可以在drl文件中以以下方式声明/使用此变量:
then you can declare/use this variable in your drl file as :
global SecurityService securityService.
PS:-可以通过以下方式获得KieRuntime对象:KieRuntime kieRuntime =(KieRuntime)kieSssion;
PS:- KieRuntime object can be obtained as: KieRuntime kieRuntime = (KieRuntime) kieSssion;
这篇关于如何在Drools规则中使用Spring Service?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!