Easy Spring-Boot with Drools
Roddy
Posted on October 8, 2021
There's a million of these articles and they're all overly complex. You can expose your Drools KieContainer
as a bean with 2 lines if you let Drools manage the rules on your classpath:
@Bean
public KieContainer kieContainer() {
KieServices kieServices = KieServices.Factory.get();
return kieServices.getKieClasspathContainer();
}
Boom. Done. No need to futz with file I/O, the KieFileSystem
, or any of that other nonsense. Drools will do it all for you if you let it -- why make your life more complicated?
For completeness, you'd use it in your components/services like this:
@Service
public class FooService {
// Inject the bean using constructor injection
private final KieContainer kieContainer;
public FooService(KieContainer kieContainer) {
this.kieContainer = kieContainer;
}
public void fireRules() {
KieBase rules = this.kieContainer.getKieBase("validaton");
KieSession session = rules.newKieSession();
try {
session.insert( ... ); // add facts into working memory
session.fireAllRules();
} finally {
session.dispose();
}
}
}
This all works if you have your rules on your classpath, with a kmodule.xml describing your kieBases in META-INF.
If you want to see a working example, my library demo application is a Spring-Boot app I developed for my series of articles about how not to interact with databases.
Cover image attribution: coyot @ PixaBay
Posted on October 8, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.