Easy Spring-Boot with Drools

roddy

Roddy

Posted on October 8, 2021

Easy Spring-Boot with Drools

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();
}
Enter fullscreen mode Exit fullscreen mode

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();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

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

💖 💪 🙅 🚩
roddy
Roddy

Posted on October 8, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Easy Spring-Boot with Drools
spring Easy Spring-Boot with Drools

October 8, 2021