How to use a Spring Service in Drools rules?

冷暖自知 提交于 2019-12-10 14:13:38

问题


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.

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?

I have followed the following indications:

  1. 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.
  2. 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?

As

File: 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

File: 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

File: 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);
    }

}

回答1:


You can use the setGlobal function of kieRuntime as:

kieRuntime.setGlobal("securityService", securityService);

then you can declare/use this variable in your drl file as :

global SecurityService securityService.

PS:- KieRuntime object can be obtained as: KieRuntime kieRuntime = (KieRuntime) kieSssion;



来源:https://stackoverflow.com/questions/43346204/how-to-use-a-spring-service-in-drools-rules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!