25.02.2015 Views

Introducing Spring Framework

Introducing Spring Framework

Introducing Spring Framework

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Doing Something Groovy<br />

Chapter 14 ■ Using Dynamic Languages<br />

Groovy is a dynamic language that sits on top of the Java virtual machine; it has powerful features inspired by<br />

Python, Ruby, and Smalltalk. Easy to create DSLs (domain-specific languages) increase the developer’s productivity<br />

by eliminating all of Java’s boilerplate code, and they integrate very well with existing Java libraries. In other words,<br />

Groovy is Java! But don’t worry about it too much, Groovy has almost a zero learning curve. You have seen it in action<br />

in Chapter 1, and you are going to use it in later chapters too.<br />

Now, back to your code. You are not going to use the existing implementation (see Listing 14-2); you are going<br />

to use the Groovy programming language as the implementation of the Login interface class. But how are you<br />

going to use a dynamic language for this? Well, because Groovy sits on top of the virtual machine, it will be easy to<br />

compile the Groovy class or script and then put it into your classpath so it can be used by your <strong>Spring</strong> application.<br />

But what happens if you need to change or add some more behavior to your Groovy class? First, you need to do the<br />

modification and compile it, then you need to re-deploy or change it for the new compiled class. That’s a lot<br />

of trouble.<br />

That is why the <strong>Spring</strong> <strong>Framework</strong> allows for the use of dynamic languages and changing them at runtime<br />

without even compiling them. Listing 14-4 shows the Groovy implementation of the Login interface.<br />

Listing 14-4. META-INF/scripts/groovylogin.groovy<br />

import com.apress.isf.java.service.Login<br />

class GroovyLoginService implements Login {<br />

String username<br />

String password<br />

}<br />

boolean isAuthorized(String email, String pass) {<br />

if(username==email && password==pass)<br />

return true<br />

return false<br />

}<br />

As you can see, Listing 14-4 is very simple. You got rid of the setters and getters and all the Java clutter. Now let’s<br />

see how the XML will look in order to use this Groovy script; see Listing 14-5.<br />

Listing 14-5. mydocuments-context.xml<br />

<br />

<br />

197

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!