Configured: Expression Based Rules

Historically, doing things you'd take for granted when building your objects in Java has always been a bit of a pain in an IOC container. Spring had various sorts of FactoryBeans that allowed you to usually achieve what you wanted, but the resulting xml was hardly intuitive and often it was eaiser to just write your own factory bean to get the job done sanely. This has been remedied to some extent in later versions of Spring by hiding the FactoryBeans behind new schema elements, but all the same, sometimes it'd be a whole lot easier if you just embed little bits of Java in the application context...

Configured has a standard rule named: SimpleScriptBasedRule which allows you to do just that. To use it in a rulebase, do something like the example below.

 <bean id="autowiringService"
        <property name="rulebase">
                  <property name="script">
                         import net.sourceforge.configured.spring.*;                            
                         if(fieldName.equals("message")) {
                             return "Hello, World!!";
                         else if (fieldType.equals(TestClassD.class)) {
                             return spring.getBean("beanD");
                        return null;
                 <property name="precedence" value="2" />
        <property name="ignoredDependencyTypes">

The default context the script executes in has the following variables available:

  • declaringClass - The class which declared the current dependency (null if root object)
  • fieldName - The name of the property on declaringClass being initialized (if there is a declaringClass)
  • fieldType - The type of the property being initialized
  • utils - An instance of net.sourceforge.configured.utils.ScriptUtils
  • spring - A reference to the ApplicationContext

    You may add more variables to the script's execution environment by using the context property on the JavaExpressionRuleFactory, which is a map of names to objects. All these names will be directly accessible in the script.