Skip to content
This repository has been archived by the owner on Apr 14, 2022. It is now read-only.

Using Spring Templates in Scala

Arjen Poutsma edited this page Oct 30, 2012 · 2 revisions

Using Spring Templates in Scala

Spring's templates are helpful utility classes that facilitate any sort of data access, or resource handling in general. In Spring Java, these templates generally operate through (anonymous inner class) callbacks:

ConnectionFactory connectionFactory = ...
JmsTemplate template = new JmsTemplate(connectionFactory);

template.send("queue", new MessageCreator() {
    public Message createMessage(Session session) throws JMSException {
        return session.createTextMessage("Hello World");
    }
});

Message message = template.receive("queue");
if (message != null && message instanceof TextMessage) {
    System.out.println(((TextMessage) message).getText());
}
else {
    System.out.println("No text message received");
}

In Scala, it makes more sense to use functions for this purpose. Spring Scala contains wrappers that adapt the 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 Option where the Java version could return null
  • Use class manifests instead of class parameters

With these three improvements, the above Java code can be written in Scala as:

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 None => println("No text message received")
}

The use of class manifests means that instead of this:

RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject("http://example.com", String.class);

you can write the following in Scala:

val template = new RestTemplate()
val result = template.getForAny[String]("http://example.com")

Scala-friendly Templates

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, and SimpleJdbcTemplate lives in org.springframework.scala.jdbc.core.simple.

As of writing this page, the following Scala-friendly templates exist:

  • SimpleJdbcTemplate
  • JmsTemplate
  • RestTemplate
  • TransactionTemplate

All of these have the three improvements mentioned above: functions, Option, and using class manifest. Please refer to the source code and ScalaDoc for more information.

TransactionManagement trait

Besides the TransactionTemplate, Spring Scala also contains the TransactionManagement trait. This trait contains a single method called transactional which takes a function as a parameter. All code in this function will be executed transactionally using standard Spring transaction management.

For instance:

class TransactionalExample extends TransactionManagement {
    val dataSoure: DataSource = ...
    val jdbcTemplate = new SimpleJdbcTemplate(dataSource)
    val transactionManager = new DataSourceTransactionManager(dataSource)

    val result: String = transactional() {
        status => {
            jdbcTemplate.queryForObject[String]("SELECT FIRST_NAME FROM USERS WHERE ID = 1")
        }
    }
}