Create Spring Beans in Your Site With Crafter CMS

DZone 's Guide to

Create Spring Beans in Your Site With Crafter CMS

Using Crafter CMS' Groovy scripting support, you can easily create and wire Spring Beans for use in your project with a simple three-step process.

· Web Dev Zone ·
Free Resource

Crafter CMS 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. Crafter CMS 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. For example, you could put them under 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:


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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 id="myAddressBook" class="fastenal.AddressBook">
    <property name="label" value="Russ's Address Book" />
    <property name="addresses">
      <ref bean="myAddressStoreMap" /> 

Step 3: Grab the Bean

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

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

Step 3.a: Showing the Count

And finally, show the count in a template:

<h1>Address Book: ${addressBook.label}</h1>
<h2>Entries: ${addressBook.addressCount}</h2>
crafter cms ,groovy ,spring beans ,tutorial ,web dev

Published at DZone with permission of Russ Danner , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}