Listing 22-13. The ContactServiceImpl Class
package com.apress.prospring3.ch22.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import
com.apress.prospring3.ch22.domain.Contact;
import
com.apress.prospring3.ch22.rule.domain.Rule;
import
com.apress.prospring3.ch22.rule.engine.RuleEngine;
import
com.apress.prospring3.ch22.rule.factory.RuleFactory;
import
com.apress.prospring3.ch22.service.ContactService;
@Service("contactService")
public class ContactServiceImpl implements ContactService {
@Autowired
ApplicationContext ctx;
@Autowired
private RuleFactory ruleFactory;
@Autowired
private RuleEngine ruleEngine;
public void applyRule(Contact contact) {
// Apply ageCategory rule
ruleFactory = ctx.getBean("ruleFactory", RuleFactory.class);
Rule ageCategoryRule = ruleFactory.getAgeCategoryRule();
ruleEngine.run(ageCategoryRule, contact);
}
}
In Listing 22-13, the required Spring beans are autowired into the service implementation class. In
the applyRule() method, the rule is obtained from the rule factory and then applied to the Contact
object. The result is that the ageCategory property for the Contact will be derived based on the rule's
defined conditions, actions, and parameters.
Implement the Rule Factory as a Spring Refreshable Bean
Now we can implement the rule factory and the rule for age category classification. We want to be able
to update the rule on the fly and have Spring check for its changes and pick it up to apply the latest logic.
The Spring Framework provides wonderful support for Spring beans written in scripting languages,
called refreshable beans. We will see how to configure a Groovy script as a Spring bean and instruct
Spring to refresh the bean on a regular interval later. First let's see the implementation of the rule factory
in Groovy. To allow dynamic refresh, we put the class into an external folder. In the project root, create a
folder called resources. The RuleFactoryImpl class (which is a Groovy class, with the name
RuleFactoryImpl.groovy) will be placed into this folder. Listing 22-14 shows the class content.
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home