DEV Community

Cover image for Easy Spring-Boot with Drools
Roddy
Roddy

Posted on

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

Top comments (1)

Collapse
 
gatrad profile image
gatrad

@roddy, Hi Can you please help me with this, from your prior experience?
stackoverflow.com/questions/749618...