Skip to content
Skip to breadcrumbs
Skip to header menu
Skip to action menu
Skip to quick search
Quick Search
Browse
Pages
Blog
Labels
Attachments
Mail
Advanced
What’s New
Space Directory
Feed Builder
Keyboard Shortcuts
Confluence Gadgets
Log In
Sign Up
Dashboard
Groovy
Copy Page
You are not logged in. Any changes you make will be marked as
anonymous
. You may want to
Log In
if you already have an account. You can also
Sign Up
for a new account.
This page is being edited by
.
Paragraph
Paragraph
Heading 1
Heading 2
Heading 3
Heading 4
Heading 5
Heading 6
Preformatted
Quote
Bold
Italic
Underline
More colours
Strikethrough
Subscript
Superscript
Monospace
Clear Formatting
Bullet list
Numbered list
Outdent
Indent
Align left
Align center
Align right
Link
Table
Insert
Insert Content
Image
Link
Attachment
Symbol
Emoticon
Wiki Markup
Horizontal rule
tinymce.confluence.insert_menu.macro_desc
Info
JIRA Issue
Status
Gallery
Tasklist
Table of Contents
Other Macros
Page Layout
No Layout
Two column (simple)
Two column (simple, left sidebar)
Two column (simple, right sidebar)
Three column (simple)
Two column
Two column (left sidebar)
Two column (right sidebar)
Three column
Three column (left and right sidebars)
Undo
Redo
Find/Replace
Keyboard Shortcuts Help
<h3>Background</h3> <p>The <a href="http://www.springframework.org/">Spring Framework</a> is a leading full-stack Java/J2EE application framework. It is aimed primarily at Java projects and delivers significant benefits such as reducing development effort and costs while providing facilities to improve test coverage and quality. It also has mechanisms for allowing beans to be backed by dynamic language code including Groovy and other languages.</p> <p>Let's have a look at how to use Spring's support for writing dynamic language backed beans to extend an existing Java application. The existing Java application prints out information about countries in sorted order. We want to be able to add new countries and new sorting algorithms but using different languages for each one. Our goal is to not have to change the original Java code but add the new features just through the application wiring.</p> <h3>The Existing Application (Spring and Java)</h3> <p>Suppose we have the following interface:</p> <table class="wysiwyg-macro" data-macro-name="code" data-macro-default-parameter="java" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGU6amF2YX0&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> package spring; public interface Country { long getPopulation(); String getCapital(); } </pre></td></tr></table> <p>And the following implementation class:</p> <table class="wysiwyg-macro" data-macro-name="code" data-macro-default-parameter="java" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGU6amF2YX0&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> package spring; public class USA implements Country { private final String capital; private final long population; public USA(String capital, long population) { this.population = population; this.capital = capital; } public String toString() { return "USA[Capital=" + capital + ", Population=" + population + "]"; } public long getPopulation() { return population; } public String getCapital() { return capital; } } </pre></td></tr></table> <p>Spring supports the <a href="http://www.martinfowler.com/articles/injection.html">Dependency Injection</a> style of coding. This style encourages classes which depend on classes like <code>USA</code> not to hard-code that dependency, e.g. no fragments of code like '<code>new USA(...)</code>' and no '<code>import ...USA;</code>'. Such a style allows us to change the concrete implementations we depend on for testing purposes or at a future point in time as our program evolves. In our example above, we might declaratively state our dependencies in a <code>beans.xml</code> file as follows:</p> <table class="wysiwyg-macro" data-macro-name="code" data-macro-default-parameter="xml" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGU6eG1sfQ&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:lang="http://www.springframework.org/schema/lang" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-2.0.xsd"> <bean id="usa" class="spring.USA"> <constructor-arg value="Washington, D.C."/> <constructor-arg value="298444215"/> </bean> </beans> </pre></td></tr></table> <p>In this example, the <code><constructor-arg/></code> element allows us to use constructor-based injection.</p> <p>Having done this, we can get access to our beans through a variety of mechanisms. Normally, access to the beans is mostly transparent. In our case though, we are going to make access explicit so you can see what is going on. Our main method might look like this:</p> <table class="wysiwyg-macro" data-macro-name="code" data-macro-default-parameter="java" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGU6amF2YX0&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> package spring; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.Arrays; public class SortMain { public static void main(String[] args) { try { ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); Country usa = (Country) ctx.getBean("usa"); System.out.println("USA Info:\n" + usa); } catch (Exception e) { e.printStackTrace(); } } } </pre></td></tr></table> <p>Running this results in:</p> <table class="wysiwyg-macro" data-macro-name="code" data-macro-default-parameter="none" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGU6bm9uZX0&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> USA Info: USA[Capital=Washington, D.C., Population=298444215] </pre></td></tr></table> <h3>Spring and Groovy</h3> <p>We can extend this example and introduce Groovy in a number of ways. Firstly, we can create the following Groovy class:</p> <table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> package spring public class Australia implements Country { String capital long population String toString() { return "Australia[Capital=" + capital + ", Population=" + population + "]" } } </pre></td></tr></table> <p>And this one too:</p> <table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> package spring public class NewZealand extends Australia implements Country { String toString() { return "NewZealand[Capital=" + capital + ", Population=" + population + "]" } } </pre></td></tr></table> <p>So long as the corresponding <code>.class</code> file is available on the classpath (e.g. by your IDE or by manually running <code>groovyc</code>), we can simply reference this class in our <code>beans.xml</code> file. E.g. for the first class we can use:</p> <table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> ... <bean id="country1" class="spring.Australia"> <property name="capital" value="Canberra"/> <property name="population" value="20264082"/> </bean> ... </pre></td></tr></table> <p>Alternatively, if the source file is on the classpath, we can use special Spring notation to reference it, e.g. for the second class we can use:</p> <table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> ... <lang:groovy id="country3" script-source="classpath:spring/NewZealand.groovy"> <lang:property name="capital" value="Wellington" /> <lang:property name="population" value="4076140" /> </lang:groovy> ... </pre></td></tr></table> <p>In these examples, the <code><property/></code> and <code><lang:property/></code> elements allows us to use setter-based injection.</p> <h3>Spring and JRuby</h3> <p>If we prefer to code in another language (with a few restrictions - see below), Spring supports other languages too, e.g.:</p> <table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> require 'java' include_class 'spring.Country' class Fiji < Country def getCapital() @capital end def getPopulation() @population end def setCapital(capital) @capital = capital end def setPopulation(population) @population = population end def to_s() "Fiji[Capital=" + @capital + ", Population=" + getPopulation().to_s() + "]" end end Fiji.new()</pre></td></tr></table> <table class="wysiwyg-macro" data-macro-name="code" data-macro-default-parameter="xml" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGU6eG1sfQ&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> ... <lang:jruby id="country4" script-interfaces="spring.Country" script-source="classpath:spring/Fiji.rb"> <lang:property name="capital" value="Suva" /> <lang:property name="population" value="905949" /> </lang:jruby> ... </pre></td></tr></table> <h3>Spring and Groovy Again</h3> <p>But wait there's more ...</p> <p>Suppose now that we wish to sort our countries according to population size. We don't want to use Java's built-in sort mechanisms as some of them rely on our objects implementing the <code>Comparable</code> interface and we don't want that noise in our Ruby script. Instead we will use Groovy. We could simply write a Sort class in Groovy and reference as we have done above. This time however we are going to use an additional Spring feature and have the scripting code within our <code>beans.xml</code> file. First we define the following Java interface:</p> <table class="wysiwyg-macro" data-macro-name="code" data-macro-default-parameter="java" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGU6amF2YX0&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> package spring; import java.util.List; public interface Sorter { List sort(Country[] unsorted); } </pre></td></tr></table> <p>We can then include the Groovy sort code directly into the <code>beans.xml</code> file as follows:</p> <table class="wysiwyg-macro" data-macro-name="code" data-macro-default-parameter="xml" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGU6eG1sfQ&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> ... <lang:groovy id="sorter"> <lang:inline-script><![CDATA[ package spring class CountrySorter implements Sorter { String order List sort(Country[] items) { List result = items.toList().sort{ p1, p2 -> p1.population <=> p2.population } if (order == "reverse") return result.reverse() else return result } } ]]></lang:inline-script> <lang:property name="order" value="forward" /> </lang:groovy> ... </pre></td></tr></table> <h3>Putting it all together</h3> <p>We now combine all of the approaches above in a final example.</p> <p>Here is the complete <code>beans.xml</code> file:</p> <table class="wysiwyg-macro" data-macro-name="code" data-macro-default-parameter="xml" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGU6eG1sfQ&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:lang="http://www.springframework.org/schema/lang" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-2.0.xsd"> <bean id="country1" class="spring.Australia"> <property name="capital" value="Canberra"/> <property name="population" value="20264082"/> </bean> <bean id="country2" class="spring.USA"> <constructor-arg value="Washington, D.C."/> <constructor-arg value="298444215"/> </bean> <lang:groovy id="country3" script-source="classpath:spring/NewZealand.groovy"> <lang:property name="capital" value="Wellington" /> <lang:property name="population" value="4076140" /> </lang:groovy> <lang:jruby id="country4" script-interfaces="spring.Country" script-source="classpath:spring/Fiji.rb"> <lang:property name="capital" value="Suva" /> <lang:property name="population" value="905949" /> </lang:jruby> <lang:groovy id="sorter"> <lang:inline-script><![CDATA[ package spring class CountrySorter implements Sorter { String order List sort(Country[] items) { List result = items.toList().sort{ p1, p2 -> p1.population <=> p2.population } if (order == "reverse") return result.reverse() else return result } } ]]></lang:inline-script> <lang:property name="order" value="forward" /> </lang:groovy> </beans> </pre></td></tr></table> <p>Our Java code to use this example looks like:</p> <table class="wysiwyg-macro" data-macro-name="code" data-macro-default-parameter="java" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGU6amF2YX0&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> package spring; import java.util.Arrays; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SortMain { public static void main(String[] args) { try { ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); Country[] countries = { (Country) ctx.getBean("country1"), (Country) ctx.getBean("country2"), (Country) ctx.getBean("country3"), (Country) ctx.getBean("country4") }; Sorter sorter = (Sorter) ctx.getBean("sorter"); System.out.println("Unsorted:\n" + Arrays.asList(countries)); System.out.println("Sorted:\n" + sorter.sort(countries)); } catch (Exception e) { e.printStackTrace(); } } } </pre></td></tr></table> <p>And the resulting output (with a little bit of hand formatting) looks like:</p> <table class="wysiwyg-macro" data-macro-name="code" data-macro-default-parameter="none" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGU6bm9uZX0&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> Unsorted: [Australia[Capital=Canberra, Population=20264082], USA[Capital=Washington, D.C., Population=298444215], NewZealand[Capital=Wellington, Population=4076140], JRuby object [Fiji[Capital=Suva, Population=905949]]] Sorted: [JRuby object [Fiji[Capital=Suva, Population=905949]], NewZealand[Capital=Wellington, Population=4076140], Australia[Capital=Canberra, Population=20264082], USA[Capital=Washington, D.C., Population=298444215]] </pre></td></tr></table> <h3>What we didn't tell you yet</h3> <ul> <li>Spring supports <a href="http://www.beanshell.org/">BeanShell</a> in addition to JRuby and Groovy</li> <li>Spring supports the concept of <em>refreshable</em> beans when using the <code><lang:<em>language</em>/></code> element so that if your bean source code changes, the bean will be reloaded (see GINA or the Spring doco for more details)</li> <li>The Groovy scripting examples in the current Spring documentation are based on an old version of Groovy, ignore the <code>@Property</code> keywords and use the latest <code>groovy-all-<em>xxx</em>.jar</code> instead of the jars they recommend</li> <li>The <code><lang:<em>language</em>/></code> element currently only supports setter-based injection</li> <li>Spring automatically converts between the object models of the various languages but there are some limitations (particularly with JRuby - see the next section)</li> </ul> <h3>Current Limitations</h3> <p>Currently using the Groovy language through Spring is extensively supported. Using other languages like JRuby takes a little more care. Try restricting your JRuby methods to ones which take and return simple data types, e.g. long and String. You may also find that certain operations don't work as you'd expect when working between Ruby and other languages, e.g. if you defined a <code>compareTo</code> method in our <code>Fiji.rb</code> file, it would return <code>long</code> by default rather than the <code>int</code> which Java is expecting. In addition, the <code>compareTo</code> method takes an <code>other</code> object as a parameter. Currently the wrapping of this <em>other</em> object from Java or Groovy into a Ruby object hides the original Java methods.</p> <h3>Further Information</h3> <ul> <li>Section 11.5 of <a href="http://groovy.canoo.com/gina">GINA</a></li> <li>Spring <a href="http://static.springframework.org/spring/docs/2.0.x/reference/index.html">documentation</a> for <a href="http://static.springframework.org/spring/docs/2.0.x/reference/dynamic-language.html">scripting</a></li> <li>The Spring example in <a class="confluence-link" href="/display/GROOVY/Groovy+and+JMX" data-linked-resource-id="79147" data-linked-resource-type="page" data-linked-resource-default-alias="Groovy and JMX" data-base-url="http://docs.codehaus.org">Groovy and JMX</a></li> </ul>
Please type the word appearing in the picture.
Attachments
Labels
Location
Watch this page
< Edit
Preview >
Loading…
Save
Cancel
Next hint
search
attachments
weblink
advanced