How-To #3: Spring Integration

Introduction

This article will show you how to integrate MRules in a project based on Spring. More precisely, we will see here how to use dependency injection with MRules and Spring.

Dependency injection

Dependency injection is a mechanism allowing to implement inversion of control. Programs using dependency injection are loosely coupled, as dependencies between software components are resolved dynamically at runtime instead of being hard coded and static.

MRules supports native CDI specified by Java EE 6 since version 1.3.0. But the Spring implementation is more powerful and can be used with JDK 1.5.

So the version 1.9.0 of MRules is shipped with a brand new extension, providing support for Spring dependency injection. See below how to use it.

Add extension to you project

The extension is shipped as a Maven dependency. A transitive dependency allows to retrieve the library core. Only one dependency declaration is necessary.

POM example for Maven :

Annotation Configuration

If you are using on your project the new annotation-oriented way to configure Spring (which is in my opinion far more elegant than the old fashioned XML files) then you will have two solutions available to integrate MRules :

With the factory

In the Spring configuration class, you will have to declare a Bean returning an instance of the MRules factory. You can extend the factory class in order to read configuration from external configuration file, database, or any other way. Then Spring will automatically use the factory instance to instanciate the rule engine.
Example :

Then, just use your rule engine in your module !

Without the factory

It’s almost the same as the factory way, but you instanciate your rule engine directly in the Spring config class instead of delegating this operation to the factory. And you use you rule engine instance the same way.

It’s a little less flexible, but may be enough depending on the context.

XML Configuration

If your Spring project is configured using XML, you will have no difficulties to integrate MRules. Just declare a bean in your Spring context configuration, as follow :

Then, just use your rule engine in your module, with the @Autowired annotation, or with the XML IOC configuration.

Demo

A demo, which can be found in the download page, illustrates all the examples above.