How to use the Spring Framework in Scala

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 17.4, “How to use the Spring Framework in Scala.”

Problem

You want to use the Java Spring Framework library in your Scala application.

Solution

In my experience, the only real changes in using the Spring Framework in Scala applications involve how you cast the objects you instantiate from your Spring application context file, and that’s only because the casting process is different between Scala and Java.

To demonstrate this, create an empty SBT project. (See Recipe 18.1, if necessary.) Within that project, create a Spring applicationContext.xml file in the src/main/resources directory with the following contents:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    <bean id="dog" class="scalaspring.Dog">
        <constructor-arg value="Fido" />
    </bean>
    <bean id="cat" class="scalaspring.Cat">
        <constructor-arg value="Felix" />
    </bean>
</beans>

This file declares that there are two classes, one named Dog and the other named Cat, in a package named scalaspring. You can’t tell it from looking at this file, but as you’ll see shortly, both the Dog and Cat classes extend a base Animal class.

Next, create a simple Scala object in a file named SpringExample.scala in the root directory of your project with a main method to read the applicationContext.xml file and create instances of the Dog and Cat classes:

package scalaspring

import org.springframework.context.support.ClassPathXmlApplicationContext

object ScalaSpringExample extends App {

    // open & read the application context file
    val ctx = new ClassPathXmlApplicationContext("applicationContext.xml")

    // instantiate the dog and cat objects from the application context
    val dog = ctx.getBean("dog").asInstanceOf[Animal]
    val cat = ctx.getBean("cat").asInstanceOf[Animal]

    // let them speak
    dog.speak
    cat.speak

}

In this code, the applicationContext.xml file is loaded, the dog and cat instances are created from their bean definitions in the application context, and their speak methods are executed.

Next, define the Dog and Cat classes in a file named Animals.scala, along with their abstract parent class Animal. You can also save this file in the root directory of your SBT project:

package scalaspring

abstract class Animal(name: String) {
    def speak: Unit     // asbtract
}

class Dog(name: String) extends Animal(name) {
    override def speak {
        println(name + " says Woof")
    }
}

class Cat(name: String) extends Animal(name) {
    override def speak {
        println(name + " says Meow")
    }
}

The base Animal class requires that the concrete classes have a speak method, and the Dog and Cat classes define their speak methods in different ways. The Dog and Cat classes are defined using a one-argument constructor, and if you look back at the application context file, you’ll see that the names Fido and Felix are used in their Spring bean definitions.

Next, add Spring as a dependency to your build.sbt file. A basic file looks like this:

name := "Scala Spring Example"

version := "1.0"

scalaVersion := "2.10.0"

libraryDependencies += "org.springframework" % "spring" % "2.5.6"

As mentioned, you should place the applicationContext.xml file in your project’s src/main/resources folder. This listing shows all the files in my project:

./Animals.scala
./build.sbt
./SpringExample.scala
./src/main/resources/applicationContext.xml

With everything in place, run the project with the usual sbt run command. You’ll see a lot of output, including these lines, showing that the program ran successfully:

$ sbt run
Fido says Woof
Felix says Meow

You can put the two Scala source files under the src/main/scala directory if you prefer, but for simple examples like this, I put them in the root directory of my SBT project.

Discussion

Although there was a bit of boilerplate work in this example, the only major differences between using Scala and Java are these two lines of code in the ScalaSpringExample object:

val dog = ctx.getBean("dog").asInstanceOf[Animal]
val cat = ctx.getBean("cat").asInstanceOf[Animal]

That’s because this is how you cast classes in Scala. In Java, these same lines of code would look like this:

Animal dog = (Animal)ctx.getBean("dog");
Animal cat = (Animal)ctx.getBean("cat");

See Also

The Scala Cookbook

This tutorial is sponsored by the Scala Cookbook, which I wrote for O’Reilly:

You can find the Scala Cookbook at these locations: