[英]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.