簡體   English   中英

如何從drools規則調用spring bean中的方法

[英]How to call method in spring bean from drools rule

我有一個 Drools 規則來檢查數據庫中是否存在一個值。 但是在我檢查之前,我需要先將值傳遞給一個 spring bean 方法進行加密,然后再檢查該值,因為數據庫中的值是加密的。

服務

public class EncryptService {
    public String encrypt(String value) {
    return encryptedValue;
    }
}

規則

rule "Check value"
    salience 10
    dialect "java"
     when
        $g: EncryptService()
        exists($g.encrypt(value))
     then
        log.info('value already exists')
end

如何調用該方法從 Spring Bean 的規則進行加密?

我嘗試過的事情

通過全局變量聲明。 像上面的例子一樣通過 new 實例化,但這不起作用,因為它是一個已經由 spring 創建的 bean。

您需要將 bean 實例傳遞到您的規則會話中,然后編寫的規則將執行您想要的操作。

例如 -

@Component
class RuleExecutor {

  private final EncryptService encryptService; // Bean set via constructor injection

  public RuleExecutor(EncryptService encryptService) {
    this.encryptService = encryptService;
  }

  public void fireRules( ... ) { // assuming other data passed in via parameter
    KieSession kieSession = ...; 
    kieSession.insert( this.encryptService ); // insert bean into the working memory
    kieSession.insert( ... );  // insert other data into working memory
    kieSession.fireAllRules();
  }
}

然后你可以在你的規則中對你的 bean 實例做一些事情:

rule "Encrypt value"
when
  SomeInput( $originalValue: value )
  $e: EncryptService() // will match the bean instance in working memory
then
  String encrypted = $e.encrypt($originalValue);
  // do stuff with encrypted value, eg: insert(encrypted)
end

語法$e: EncryptService()不會新建一個實例。 它匹配工作內存中現有的 EncryptService 實例,沒有其他限制。 這與您執行$car: Car( doors == 4, color == "red")之類的操作的邏輯相同——這不會使用這些變量創建 Car 的新實例,而是找到 Car 的一個實例工作內存中的這些限制並將它們分配給變量 $car。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM