Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 5 Next »

Spring and Java

The Spring Framework 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.

Let's have a look at Spring in action for a Java application which prints out information about a country.

Suppose we have the following interface:

And the following implementation class:

Spring supports the Dependency Injection style of coding. This style encourages classes which depend on classes like USA not to hard-code that dependency, e.g. no fragments of code like 'new USA(...)' and no 'import ...USA;'. 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 beans.xml file as follows:

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:

Running this results in:

Spring and Groovy

We can extend this example and introduce Groovy in a number of ways. Firstly, we can create the following Groovy class:

And this one too:

So long as the first class is available on the classpath in compiled form, we can simply reference this class in our beans.xml file as follows:

Alternatively, if the source file will be on the classpath, we can use:

Spring and Ruby

If we prefer to code in another language (with a few restrictions - see below), Spring supports other languages too, e.g.:

Putting it all together

We now combine all of the approaches above in a final example. First we need to introduce an additional interface:

We also introduce an additional approach which is to include Groovy code directly into the beans.xml file as follows:

Our Java code to use this example looks like:

And the resulting output (with a little bit of hand formatting) looks like:

Current Limitations

Currently using the Groovy language through Spring is extensively supported. Using other languages like Ruby takes a little more care. Try restricting your Ruby methods to ones which take and return simple data types, e.g. long, String and you may find that certain operations don't work as you'd expect when working between Ruby and other languages.

  • No labels