img
.
Using Groovy with Spring
The main benefit that Groovy and other scripting languages bring to Java-based applications is the
support of dynamic behavior. By using a closure, business logic can be packaged as an object and passed
around the application like any other variables.
Another main feature of Groovy is the support for developing DSLs by using its simplified syntax
and closures. As the name implies, a DSL is a language targeted for a particular domain with very specific
goals in design and implementation. The objective is to build a language that is understandable not only
by the developers but the business analysts and users as well. Most of the time, the domain is a business
area. For example, DSLs can be defined for customer classification, sales charge calculation, salary
calculation, and so on.
In this section, we will demonstrate using Groovy to implement a simple rule engine with Groovy's
DSL support. The implementation is referencing the sample from the excellent article on this topic at
www.pleus.net/articles/grules/grules.pdf, with modifications. In addition, we will discuss how
Spring's support of refreshable beans enables the update of the underlying rules on the fly without the
need to compile, package, and deploy the application.
In this sample, we will implement a rule used for classifying a specific contact into different
categories based on their age, which is calculated based on their date of birth property.
Adding Required Dependencies
In the sample, we will use Groovy and the JodaTime library, so we need to add the required
dependencies in Table 22-1 to our project.
Table 22-1. Maven Dependencies for Groovy and JodaTime
Group ID
Artifact ID
Version
Description
1.8.5
Groovy library
org.codehaus.groovy
groovy
2.0
JodaTime date-time type library
joda-time
joda-time
The Contact Domain
As mentioned, a DSL targets a specific domain, and most of the time the domain is referring to some
kind of business data. For the rule we are going to implement, it was designed to be applied to the
domain of contact information.
So, the first step is to develop the domain object model we want the rule to apply to. In this sample,
the DOM is very simple and contains only one Contact entity class, as shown in Listing 22-7. Note that
it's a POJO class like what we did in previous chapters.
Listing 22-7. The Contact Domain
package com.apress.prospring3.ch22.domain;
import org.joda.time.DateTime;
public class Contact {
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home