I have a service that is managed by spring and I want to use or inject as dependency in drool rule. How can I use the service bean in the Drool rule?
@Service
public class SomeService {
public void doSomething() {}
}
dialect "mvel"
rule "something"
when
................
then
service.doSomething()
end
Pass your bean instance into working memory when you invoke them, the same as you'd pass any other data in. This way you can autowire or otherwise leverage dependency injection to get your Spring-managed singleton bean, and then use that same bean in your rules without having to new up another instance.
@Component
class RuleExecutor {
private final SomeService service; // Bean set via constructor injection
public RuleExecutor(SomeService service) {
this.service = service;
}
public void fireRules( ... ) { // assuming other data passed in via parameter
KieSession kieSession = ...;
kieSession.insert( this.service); // insert bean into the working memory
kieSession.insert( ... ); // insert other data into working memory
kieSession.fireAllRules();
}
}
In this example I used constructor injection to pass in the bean instance. We can assume that both the @Service
and this @Component
were picked up by the component scan.
Then you could interact with it in the rules in the same way as you'd do any other data:
dialect "mvel"
rule "something"
when
service: SomeService()
then
service.doSomething()
end
Remember that service: SomeService()
matches an instance of SomeService in working memory and assigns it to the service
variable for use in the rule. It does not new up a new instance.
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.