Friday, February 13, 2009

Trivial Clojure and Spring Example

This is trivial example that shows how to use Clojure with Spring.

First, define and compile Hello.java, which has a getGreeting method.

public class Hello {
public String getGreeting() {
return "Hello, Alonzo Church";
}
}

Second, write a Spring hello.xml context, which defines a hello bean based on the Hello class.

<beans default-lazy-init="true"
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="hello" class="Hello"/>
</beans>

Finally, create a clj file that uses the Spring context to get the bean and invoke its getGreeting method.

(import '(org.springframework.beans.factory.xml XmlBeanFactory)
'(org.springframework.core.io FileSystemResource))

(let [factory (XmlBeanFactory. (FileSystemResource. "hello.xml"))
hello (. factory (getBean "hello"))]
(println (. hello getGreeting)))

To run it, include clojure.jar, spring.jar, and commons-logging.jar in your classpath.

No comments: