Welcome to Scribd, the world's digital library. Read, publish, and share books and documents. See more
Standard view
Full view
of .
Look up keyword
Like this
0 of .
Results for:
No results containing your search query
P. 1


Ratings: (0)|Views: 51 |Likes:
Published by Leonardo Linden

More info:

Published by: Leonardo Linden on Jul 28, 2011
Copyright:Attribution Non-commercial


Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less





DZone, Inc.
   G  e   t   M  o  r  e   R  e   f  c  a  r   d  z   !
   S  p  r   i  n  g    R  o  o  :
   O  p  e  n  -   S  o  u  r  c  e   R  a  p   i   d   A  p  p   l   i  c  a   t   i  o  n   D  e  v  e   l  o  p  m  e  n   t  w   i   t   h   J  a  v  a
About Spring Roo
Architectural Overview
First Hops
But Wait... There’s More!
Tips & Tricks
Hot Tips and more...
By Stefan Schmidt 
Spring Roo:
Open-Source Rapid Application Development or Java
Spring Roo is a popular open-source rapid applicationdevelopment (RAD) tool or Java developers. It enables thedeveloper to build best-practice, high-quality, lock-in-reeenterprise applications in minutes – a task that would otherwisetake days i not weeks. Developers using Roo can undamentallyand sustainably improve their productivity without compromisingengineering integrity or exibility. Roo is highly modular: it allowsdevelopers to extend its unctionality by installing new add-ons ina secure and trusted way. You can load the Spring Roo shell in the background and let itmonitor your project or directly interact with it by issuing shellcommands. The shell oers many usability eatures such as tabcompletion, context awareness, help and hinting support andautomatic roll-back. Roo even keeps a log o your shell commandsso you can easily replay them i desired.
Projects created with Spring Roo are standard Java enterpriseapplications using the Spring Framework. This means you’llfnd all the typical artiacts such as Java source fles, XMLconfguration fles, properties fles and view artiacts such as jspxfles in your project. Besides automatic confguration o Mavenbuild artiacts, logging and dependency injection, Roo allows youto connect to or transparently create new backend databases. Itachieves that by automatically confguring the Spring applicationcontext or your database and object relational mapping (ORM)tool through the Java Persistence API (JPA) standard. Transactionmanagement is also confgured out o the box. Furthermore, itcan take care o maintaining your JUnit integration tests, Webront-ends and other common project layers.
Spring Roo’s unique approach
One o the major benefts o using Spring Roo is its deepintegration o AspectJ’s inter-type declaration (ITD) eatures. Thisallows Roo to automatically produce and maintain boiler-platecode such as getter and setter methods in a dierent compilationunit (the .aj fle). AspectJ ITD fles are kept separate rom thenormal .java code you’d write as a developer so Roo can maintainthe fle’s liecycle and contents completely independently o whatever you are doing to the .java fles. Your .java fles do notneed to do anything unnatural like reerence the generated ITDfle and the whole process is completely transparent.Spring Roo selectively merges the best o the passive and activecode generation models. Roo will passively ‘watch’ (i.e., readand monitor) any activity in your project’s .java sources andautomatically adjust the AspectJ ITDs in the background tosupport your activities. For example, typical domain classes onlycontain feld defnitions that are either added through Roo shellcommands (passive generation – the user asks or it) or manuallyadded by the developer in the IDE. Boilerplate code liketoString(), accessors and mutators or the felds as well as manyother unctionalities are then transparently added and managedin the ITDs. Roo will actively make adjustments in the ITDs whenthe developer renames or deletes the feld rom his Person.javafle. Note that source code members like the toString() orgetName() and setName() methods in a separate fle (.aj) are ullyavailable or code completion in modern IDEs such as STS andIntelliJ thanks to ully integrated support or AspectJ Eclipse.
Spring Roo:
Open-Source Rapid Application Development with Java
DZone, Inc.
Since the ITDs are not expected to be edited by the developer,Roo can manage the contents o an ITD actively. This allows Rooto integrate new eatures in Spring Framework once they becomeavailable or make the code more efcient simply by updating theITD sources when upgrading to a new version o Spring Roo.
A development-time only tool
The ITD fles are automatically managed by the Spring Rooshell, which is kept running in the background while developingyour project. The contents o the ITDs can be controlled andcustomized by Java annotations placed in your .java sourcefles. These annotations always start with @Roo and are source-level retention only: hence, they are not compiled in your .classfles. This means that Roo-managed applications deployed toproduction environments have absolutely no dependency on Rooitsel. You can observe this by taking a look at your applicationruntime classpath; or example, in Web applications, your WEB-INF/lib directory will contain no Roo-related JARs.The use o Spring Roo as a productivity RAD tool that is presentonly at development time brings many advantages; you avoidlock-in, keep ull exibility or uture extensions and gainbetter perormance due to the absence o additional runtimedependencies. Furthermore, there is no scope or possible Roobugs to aect your project, and there is no risk o upgrading to alater version o Roo due to the lack o executable code anywherein your project classpath.
Roo’s deault architecture
Depending on the requirements o the application, there are anumber o approaches to designing and subsequently layering aJava enterprise application. Persistence logic is oten encapsulatedin a Data Access Object (DAO) layer in combination with anadditional repository layer. In ront o these persistence layers,developers requently use a açade or service layer, which cancontain business logic that applies to multiple domain types.In MVC-style Web applications, there is a controller layer andfnally there is a domain layer. There are ,o course, any number o alternative approaches to architecting enterprise Java applications.In a typical Roo application, you’ll only use an entity layer (whichis similar to a domain layer) and a web layer. An optional serviceslayer might be added i your application requires it, although aDAO layer is rarely added. The domain entity approach taken byRoo is conceptually related to the active record pattern employedby many modern RAD rameworks. Through the use o separateITDs or adding dierent unctionalities to a target type, Rooapplications still adheres to the separation o concerns principle.For more inormation on high-level eatures and conceptsemployed by Spring Roo, reer to the frst sections o thereerence documentation.
Spring Roo is easy to install as standalone tool and runs onWindows, Mac OSX and Linux alike. Integrated developmentenvironments (IDEs) or Java such as the SpringSource Tool Suite(STS), Eclipse (+ AJDT) and JetBrains IntelliJ also integrate SpringRoo directly into their toolset.The only prerequisites or running the Spring Roo shell are a workingJava 6 SDK and Apache Maven (2.0.9+) installation. Once thesetwo are installed, you can go ahead and download and unpackthe Spring Roo distribution. You can fnd the ~7MB download orthe latest release o Spring Roo athttp://www.springsource.com/download/community?project=Spring%20Roo. Once downloaded,simply unpack it into and add it to your path. Windows users canadd %ROO_HOME%\bin to their path and *nix users can create asymbolic link to $ROO_HOME/bin/roo.sh.Alternatively, you can install STS, which includes an integrated versiono the Spring Roo shell without any need or urther confguration.Once this is complete, you can simply start your Spring Roo shellin a resh directory:
The Spring Roo shell
The Spring Roo shell oers hinting support or newcomers.This way you can learn about the suggested steps beginningwith the creation o a new project, ollowed by confguration o persistence eatures to the creation o your frst domain classes.Tab completion plays a central role when using the SpringRoo shell. By simply hitting the Tab key, the Roo shell will oercommands, command attributes or even brie comments aboutthe unctionality oered by a command or a command attribute.Typing the frst letters o a command ollowed by Tab willcomplete the command. Subsequent uses o Tab will completemandatory command attributes until a user selection or input isrequired. Note, the integrated Roo shell in STS uses the Ctrl +Space key combination amiliar to Eclipse users in lieu o the Tabcompletion in the standalone Roo shell.The Roo shell will automatically hide commands, which are notapplicable in the current context. For example, the ‘persistencesetup’ command will not be shown when using Tab beore anew project has been created using the ‘project’ command. Rooalso oers help or any o the commands it oers. To see helpdetails or the ‘persistence setup’ command, simply type ‘helppersistence’ and Roo will present a short description and also allmandatory and optional command attributes along with a brie description or each. Finally, the Roo shell will automatically roll-back changed fles in case a problem is encountered.
 Your frst Roo project
The frst action to take in a new Spring Roo managed project is tocreate a new project:
roo> project –topLevelPackage net.addressbookCreated /home/sschmidt/AddressBook/pom.xmlCreated SRC_MAIN_JAVACreated SRC_MAIN_RESOURCESCreated SRC_TEST_JAVACreated SRC_TEST_RESOURCESCreated SRC_MAIN_WEBAPPCreated SRC_MAIN_RESOURCES/META-INF/springCreated SRC_MAIN_RESOURCES/META-INF/spring/applicationContext.xmlCreated SRC_MAIN_RESOURCES/log4j.properties
As you can see, Roo has created a standard Maven project layoutwith a Spring application context and a Log4J confguration.Ater the creation o the project, you can type ‘hint’ and ollowthe suggestions or your next steps. Note, the integrated ‘hinting’support is context sensitive. This means that the ‘hint’ commandis aware o state o your project and adjusts its suggestionsaccordingly. For example, ater the creation o a new project, the‘hint’ command will suggest to confgure your persistence setup.
Spring Roo:
Open-Source Rapid Application Development with Java
DZone, Inc.
Then in the same ashion, you can create your frst domain entity(along with a JUnit integration test) and create a ew felds or it:
roo> entity --class ~.domain.Person --testAutomatically
~.domain.Person roo> eld string --eldName name~.domain.Person roo> eld date --eldName birthDay --type java.util.Date
O course, you can refne your domain model through the SpringRoo shell or directly in your .java source code, create new types,felds, reerences, etc.Once your work is complete, you may want to test the integrity o your domain model by running the Roo generated integration tests. You can do that by running ‘perorm tests’ in the Roo shell, ‘mvn test’in your normal shell or through your IDE. The integration tests willexecute against your confgured database and the test data will becleaned up automatically ater the tests have completed.
Taking a look at the source code
A quick look at Person.java reveals the advantage o usingAspectJ ITDs:
package net.addressbook.domain;import org.springframework.roo.addon.entity.RooEntity;import org.springframework.roo.addon.javabean.RooJavaBean;import org.springframework.roo.addon.tostring.RooToString;
import java.util.Date;
import javax.persistence.Temporal;import javax.persistence.TemporalType;
import org.springframework.format.annotation.DateTimeFormat;
@RooJavaBean@RooToString@RooEntitypublic class Person {private String name;@Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(style = “S-”)private Date birthDay;
As mentioned beore, the repetitive boilerplate code or things likethe toString() method, mutators and accessors are managed bySpring Roo in separate AspectJ ITDs in the background, leavingyou with a more concise code artiact that is much easier to manageand comprehend. Roo has also taken care o correctly confguredJPA annotations (such as @Temporal) and Spring annotations (suchas @DateTimeFormat) to your felds where appropriate to providecorrect persistence and conversion behavior. You’ll notice the@RooToString annotation has also been added automatically thattriggers Roo to produce the ollowing ITD:
package net.addressbook.domain;import java.lang.String;privileged aspect Person_Roo_ToString { public String Person.toString() {
StringBuilder sb = new StringBuilder();sb.append(“Name: “).append(getName()).append(“, “);sb.append(“BirthDay: “).append(getBirthDay());
return sb.toString();}}
 You will notice that the toString() method looks just like a normalJava method with the only dierence o the AspectJ target typedefnition in ront o the method name. Furthermore, AspectJtype defnitions use the ‘privileged aspect’ defnition instead o ‘public class’ you would see in typical Java sources.As discussed in the previous section, Spring Roo integrates allpersistence related unctionality through an ITD into the targettype. This allows or a lean architecture without compromising onunctionality or exibility. Take a look into the Person_Roo_Entity.aj ITDto see the code generated and maintained by Roo. By deault Roowill generate the ollowing methods to support persisting your Persondomain entity (listing contains the most relevant methods only):
Method NamePurpose
void persist()
Save a new person record.
Person merge()
Update an existing person record.
void remove()
Remove an existing person record.
Person fndPerson(ID)
Find a person record by ID.
List<Person> fndAllPeople()
Retrieve a list o all persistent Person records.
List<Person>fndPersonEntries(rom, to)
Retrieve a list o persistent Person records or agiven range.
long countPeople()
Return a count o all Person records.
roo> controller all --package ~.web
This command will automatically scaold a complete Spring MVCWeb UI which eatures:
Best-practice Spring MVC out o the box
REST support (JSON integration optional)
Round tripping o view artiacts (jspx)
Customizable tag library (tagx)
Integrated templating support (Tiles)
Theming support (Spring MVC & CSS)
Pagination support
i18n & i11n built-in
Form validation based on JSR 303
Rich Dojo UI widgets or data selectors, etc
 You can easily deploy your Web application to the confguredTomcat or Jetty Web containers in your project by issuing ‘mvntomcat:run’ or ‘mvn jetty:run’ respectively and then navigate toyour Web application in a Web browser:I you preer a UI scaolded using Google Web Toolkit (GWT),you can issue the ollowing command:

You're Reading a Free Preview

/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->