I have a Drools rule that checks if a value exists in the database. But before I check I need to pass the value to a spring bean method to encrypt before checking the value, because the values in the database are encrypted.
Service
public class EncryptService {
public String encrypt(String value) {
return encryptedValue;
}
}
Rule
rule "Check value"
salience 10
dialect "java"
when
$g: EncryptService()
exists($g.encrypt(value))
then
log.info('value already exists')
end
How can I call that method to encrypt from the rule for a Spring Bean?
Declaring via a global variable. instantiating via new like in the example above, but that won't work because it's a bean that was already created by spring.
You need to pass the bean instance into your rule session, then the rule as written would do what you want it to.
For example --
@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();
}
}
Then you could do things against your bean instance in your rules:
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
The syntax $e: EncryptService()
doesn't new up an instance. It matches an existing instance of EncryptService in working memory with no other restrictions. It's the same logic as you would do something like $car: Car( doors == 4, color == "red")
-- this doesn't create a new instance of Car with those variables, it finds an instance of Car with those restrictions in working memory and assigns them to the variable $car.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.