Create Spring Beans in Your Site with CrafterCMS

CrafterCMS supports scripting in Groovy.  It’s awesome.  It’s lightweight. It’s fast. It’s easy.  That said when solutions start to become more sophisticated developers need ways to manage the complexity.  Spring bean factory is an inversion of control implementation that has become a standard for wiring components of a system together.  CrafterCMS lets you create classes in Groovy and wire them together as spring beans that can be used by other scripts in the system.

Step 1: Create your classes

Put your classes under scripts/classes/groovy
I.E., scripts/classes/groovy/mysite/AddressBook.groovy

Note: In older versions of Crafter (2.5.x) The path for classes is outside of the scripts folder.  For these older versions, the path is: classes/groovy/YOUR_PACKAGE/YOUR_CLASS.groovy

package mysite

import java.util.Map

public class AddressBook {

   def addresses  // map
   def label

   public int getAddressCount() {
      return addresses.size() 
   }
}

Step 2: Wire your Spring beans

Place your Spring bean configuration at the following path:

config/spring/application-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">


  <bean id="myAddressStoreMap" class="java.util.HashMap">
  </bean>
 
  <bean id="myAddressBook" class="fastenal.AddressBook">
    <property name="label" value="Russ's Address Book" />
    <property name="addresses">
      <ref bean="myAddressStoreMap" /> 
      </property>
 </bean>
</beans>

Step 3: In a Controller, get a hold of the bean and use it

templateModel.addressBook = applicationContext.get("myAddressBook")

Step 3.a Show the count in a template

<h1>Address Book: ${addressBook.label}</h1>
<h2>Entries: ${addressBook.addressCount}</h2>