Introducing Spring Scala |

Last October, at SpringOne2GX, I introduced the Spring Scala project to the world. Since then, I've also presented this project at Devoxx. In this blog post, I would like to give further details about this project and how you can use it in your Scala projects.
Why Spring Scala?
The goal of the Spring Scala project is simply to make it easier to use the Spring framework in Scala. We believe that there are many Spring users out there who want to try Scala out, but do not want to leave their experience with Spring behind. This project is meant for those people.
Obviously, you can use the (Java) Spring Framework in Scala today, without Spring Scala. But doing so will be awkward in certain places. Just like any programming language, Scala has its own, different way of doing things, and using a pure Java framework like Spring in Scala will just feel "too Java-esque". Spring Scala tries to fix this by making Spring a first-class citizen of the Scala language.
Spring Scala Overview
Spring Scala is a work in progress. In the rest of this post, I will focus on the features that are currently implemented. However, we expect many additional features to be added in the coming months, hopefully through feedback that you provide us. So if you have an idea for a feature that will make Spring more enjoyable to use in Scala, please let us know by filing a JIRA issue or leaving a comment.
Wiring up beans in XML
The easiest and preferred way to wire up a Scala Bean in a Spring XML application context is to use constructor injection. For example, imagine we have the following Scala class:
class Person(val firstName: String, val lastName: String)
You can wire up this class like so, using the c namespace:
<bean id="person" class="Person" c:firstName="John" c:lastName="Doe"/>
Note that, by using constructor injection in combination with a val, we also made the Person class immutable. Functional languages, such as Scala, encourage immutable data structures. As such, constructor injection is preferred when using Spring in Scala. Also note that constructor injection works out-of-the-box; you do not need the Spring Scala jar on the class path for it to work.
When it comes to setter injection, things become a bit more complicated. By default, Scala classes do not follow the JavaBeans property contract (eg. String getFoo() and void setFoo(String)). Instead, Scala has its own property contract: "getters" aren't prefixed by get, but rather use the field name as method name (eg. foo: String). Scala setters suffix the field name with _= (eg.foo_=(String): Unit).
To work around this issue, you can either instruct the Scala compiler to generate JavaBeans getters and setters by using the @scala.reflect.BeanProperty annotation; or you can add Spring Scala to your class path to enable support for Scala setters.
Using @BeanProperty is as simple as annotating a var with it:
class Person(@BeanProperty var firstName: String, @BeanProperty var lastName: String)
This will result in JavaBean-style setters being created for this class, so that you can wire it up in XML quite simply:
<bean id="constructor" class="Person" p:firstName="John" p:lastName="Doe"/>
As alternative to using this annotation, as of version 3.2, Spring supports arbitrary getters and setters using the BeanInfoFactory strategy interface. The Spring Scala project contains an implementation of this interface that supports Scala getters and setters. This implementation will automatically be detected by Spring, there is no need for additional configuration.
In practical terms, this means that putting the Spring Scala jar on the class path will enable support for Scala properties, and that you can use the above XML configuration to wire up the Person class without adding @BeanProperty annotations.
For more information about wiring up Scala beans in Spring XML, refer to the relevant section of the Spring Scala documentation wiki. Also take a look at the section on wiring up Scala Collections in Spring XML.
Wiring up beans in Scala
In addition to defining beans in XML, Spring Scala offers an alternative that uses Scala classes instead of XML files to configure your Spring beans. This approach is similar to using @Configuration in Spring Java, except that it is based on functions rather than annotations.
To create a functional Spring configuration, you simply have to mix in the FunctionalConfiguration trait into your configuration class. Beans are defined by calling the bean method on the trait and passing on a function that creates the bean.
Given the Person class shown above, we can wire it up in a functional configuration as follows:
class PersonConfiguration extends FunctionalConfiguration {
bean() {
new Person("John", "Doe")
}
}
Of course, you can also register a bean under a specific name, provide aliases, or set the scope:
class PersonConfiguration extends FunctionalConfiguration {
bean("john", aliases = Seq("doe"), scope = BeanDefinition.SCOPE_PROTOTYPE) {
new Person("John", "Doe")
}
}
You can then use this configuration class to create a Spring application context:
object PersonConfigurationDriver extends App {
val applicationContext = new FunctionalConfigApplicationContext(classOf[PersonConfiguration])
val john = applicationContext.getBean(classOf[Person])
println(john.firstName)
}
For more information about Functional Bean Configurations, including sections on strongly-typed bean references, how to import XML files and @Configuration classes and how to wrap bean definitions in profiles, refer to the relevant section of the Spring Scala documentation wiki.
Using Spring Templates in Scala
Spring's templates are helpful utility classes that facilitate any sort of data access, or resource handling in general. Spring Scala contains wrappers that adapt the (Java) templates to be more Scala friendly. In general, these Scala template wrapper contain three improvements over the Java version when in comes to usage in the Scala language:
- Use of functions instead of callback interfaces
- Use of
Optionwhere the Java version could returnnull - Use class manifests instead of class parameters
With these three improvements, you can use the JmsTemplate, for example, as follows:
val connectionFactory : ConnectionFactory = ...
val template = new JmsTemplate(connectionFactory)
template.send("queue") {
session: Session => session.createTextMessage("Hello World")
}
template.receive("queue") match {
case Some(textMessage: TextMessage) => println(textMessage.getText)
case _ => println("No text message received")
}
In general, the Scala version of the template wrappers live in the same package as their Java counterparts, except that there is a scala package in between. So the Scala version of the JmsTemplate lives in org.springframework.scala.jms.core, for instance. As of writing this post, the following Scala-friendly templates exist:
- SimpleJdbcTemplate
- JmsTemplate
- RestTemplate
- TransactionTemplate
For more information about using the Spring Templates in Scala, refer to the relevant section of the Spring Scala documentation wiki.
Availability
A first milestone of Spring Scala is available for download at our milestone repository, http://repo.springsource.org/libs-milestone. For Maven users:
<repositories>
<repository>
<id>milestone.repo.springsource.org</id>
<name>repo.springsource.org-milestone</name>
<url>https://repo.springsource.org/libs-milestone</url>
</repository>
</repositories>
<dependency>
<groupId>org.springframework.scala</groupId>
<artifactId>spring-scala</artifactId>
<version>1.0.0.M2</version>
</dependency>
The project itself is available at GitHub. If you would like to contribute, you can do so by filing a JIRA for a feature request, or by leaving a pul request at GitHub.
Note that as of 2013-04-02, a new milestone has been published. Read the forum announcement.
Similar Posts
- Introducing Spring Integration Scala DSL
- What's a FactoryBean?
- XPath Support in Spring Web Services
- Spring Java Configuration Moving Ahead
- What's New in Spring Integration 2.2.RC1 (Part 1 – MongoDb)




ittay says:
Added on December 10th, 2012 at 7:22 amDoes it support wiring functions? Say Person has an attribute 'eat' that is a function type Food=>HungryState. And there is an object/class with a 'skinny' function value. Can I wire Person.eat to skinny?
Mark says:
Added on December 10th, 2012 at 7:44 amThanks for this. This will make Scala more fun to use in terms of Spring.
Arjen Poutsma (blog author) says:
Added on December 10th, 2012 at 7:51 am@Ittay: not yet, feel free to file a JIRA!
@Mark: great!
Ivan says:
Added on December 10th, 2012 at 10:04 amIs there any kind of project, for akka scala spring framework?
Bryan says:
Added on December 10th, 2012 at 6:31 pmnew FunctionalConfigApplicationContext(classOf[PersonConfiguration])
applicationContext.getBean(classOf[Person])
Using classOf[T] as a parameter is clunky and is rarely seen in Scala code. They should be parameterised (and use implicit ClassManifest to get at the actual class) so the usage would be:
new FunctionalConfigApplicationContext[PersonConfiguration]
applicationContext.getBean[Person]
Also a small thing but in the example given the match is not exhaustive so case _ would be better :
template.receive("queue") match {
case Some(textMessage: TextMessage) => println(textMessage.getText)
case None => println("No text message received")
}
lshoo says:
Added on December 10th, 2012 at 10:01 pmNice!
I hope use spring scala now! Thanks!
Arjen Poutsma (blog author) says:
Added on December 11th, 2012 at 4:23 am@Ivan: I believe Josh Long has done some work on Spring support for Akka, but I don't know what state it is in. I will ask him to respond.
@Bryan: Good points. I am actually using class manifests in other places (RestTemplate for instance), but I didn't think of using it here. I have filed a JIRA issue to fix this.
@Ishoo: Thank you!
Sam Brannen (blog author) says:
Added on December 16th, 2012 at 1:51 pmNice work, Arjen. Keep it coming!
Quick question: why did you opt to scala-ify SimpleJdbcTemplate instead of JdbcTemplate, since SimpleJdbcTemplate has been deprecated since 3.1?
Just curious,
Sam
Arjen Poutsma (blog author) says:
Added on December 18th, 2012 at 4:41 am@Sam
The plan is to replace the SimpleJdbcTemplate with a Scala version of (NamedParameter)JdbcTemplate in milestone 2.
web template says:
Added on December 20th, 2012 at 5:21 amGood web template on web design, it will help you make a better web design job. Thank you for the information you provide.
Adrian says:
Added on January 12th, 2013 at 8:52 amI am trying to get the repository code to compile in Eclipse (Juno) so i can run the tests. I keep getting errors like
org.springframework.beans.factory.config.AbstractFactoryBean[T] does not have a constructor
(in source file Function0FactoryBean.scala)
class Function0FactoryBean[T](function: Function0[T], objectType: Class[T])
extends AbstractFactoryBean[T] {
I am using 3.2 of spring source and M1 of the spring scala. Scala 2.10 but 2.9 had the same issue.
Thanks for any help.
Adrian says:
Added on January 12th, 2013 at 3:29 pmLooks like there are some issues with 2.10 scala. They have deprecated ClassManifest so im getting this error
java.lang.NoClassDefFoundError: scala/reflect/ClassManifest
Even for very simple example
object Bootstrap {
val config = new FunctionalConfiguration {
bean(name = "foo", aliases = Seq("bar")) {
"Foo"
}
}
def main(args: Array[String]): Unit = {
println("Hellof")
}
}
Manuel says:
Added on January 18th, 2013 at 3:49 pmscala.reflect.BeanProperty is deprecated, it´s better using scala.beans.BeanProperty
Arjen Poutsma (blog author) says:
Added on January 21st, 2013 at 4:30 am@Adrian: I am not an Eclipse user, so I can't really help you with the first problem. It works fine in gradle. In regard to the issues with Scala 2.10: I will investigate and fix that this week.
@Manuel: Good to know, thanks!
Adrian says:
Added on February 3rd, 2013 at 4:04 pmThanks Manuel.
Is that something i can do as an end user of a library or does the library have to be re coded to use scala.beans.BeanProperty by spring dev team?
Any more updates of when a new miletstone is coming out?
Arjen Poutsma (blog author) says:
Added on February 4th, 2013 at 4:09 am@Adrian: we don't use BeanProperty in Spring Scala, so there is no need for us to update anything. In fact: the native property support we offer in Spring Scala drops the need for BeanProperty all together.
However, Scala 2.10 did introduce some other breaking changes which broke the native property support. So if you are using Scala 2.10, you will need to build from sources until we release a new milestone. Instructions to do so are in the README: https://github.com/SpringSource/spring-scala/blob/master/README.md
Adrian says:
Added on February 5th, 2013 at 3:33 pmThanks Arjen
That worked. Built the source with 2.10 scala installed and the build worked like a charm.
For anyone else as clueless as me the steps i followed were.
1. Have Scala 2.10 installed
2. Follow the instructions at the github page ( i dont think you even need gradle bin distribution on your machine – it seemed to download that too when you execute the gradlew command)
3. It created a jar in the lib dir of the pulled git files created in 2
4. It worked for me for a very simple example using the spring 3.2 RC2 jars e.g. spring-core-3.2.0.RC2.jar
Alois Cochard says:
Added on February 8th, 2013 at 1:47 amAnd what about using a Scala DSL instead of this horrible XML configuration?
Or maybe users have better to go with http://github.com/aloiscochard/sindi in this case
Arjen Poutsma (blog author) says:
Added on February 8th, 2013 at 3:46 am@Alois
If you had read the article more carefully, you would have noticed that XML configuration is optional and by no means required. There is a type safe Scala DSL to configure beans as well.
Alois Cochard says:
Added on February 8th, 2013 at 12:18 pm@Arjen
Yeah I confess that I missed that part as I first the read the article in diagonal and then jumped to source code, and seen FunctionalConfiguration later.
You can still run into runtime exception, because the context is only validated once executed.
BTW, what I meant about safety when discussing on twitter was more about the different API, like the REST one for example (but in others too) where there is bunch of Any/Any*
You might be interested to take look at the great Spray.io routing DSL, and then dive into Shapeless, it's a very powerful tool for creating poly-typed DSL.
I'm afraid I won't spent time trying to improve that as a PR as you asked me, I haven't using Spring since 3 years (when I started coding professionaly in Scala) and have no plan to use it in future.
But I might add a spring-compatibility layer into Sindi if I see users are interested, I'll probably anyway wait for macro-paradise to be released as it should be then pretty easy to load and validate XML context at compile time and integrate them nicely through implicits.
If that sounds interesting to you I would love sharing some ideas or
collaborating on this as I think it would be a nice way to support migration of legacy spring app in Scala without loosing safety.
lshoo says:
Added on March 20th, 2013 at 10:10 pmHi, Can you show some spring-scala with springmvc example?
Thanks!