Spring Roo 1.1 Cookbook

By Ashish Sarin
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Getting Started with Spring Roo

About this book

Spring Roo is an easy-to-use productivity tool for rapidly developing Java enterprise applications using well-recognized frameworks such as Spring, Hibernate, AspectJ, Spring Web Flow, Spring Security, GWT, and so on. Spring Roo takes care of creating maven-enabled projects, enterprise application architecture based on your choice of technologies, unit/integration tests based on your choice of testing framework, and so on. The bottom line is that if you're using Spring, then you must consider using Spring Roo for increased productivity.

Spring Roo 1.1 Cookbook brings together a collection of recipes that demonstrate how the Spring Roo developer tool simplifies rapidly developing enterprise applications using standard technologies/frameworks such as JPA, GWT, Spring, Flex, Spring Web Flow, Spring Security, and so on. It introduces readers to developing enterprise applications for the real world using Spring Roo tool. The book starts off with basic recipes to make readers comfortable with using Spring Roo tool. As the book progresses, readers are introduced to more sophisticated features supported by Spring Roo in the context of a Flight Booking application. In a step-by-step by fashion, each recipe shows how a particular activity is performed, what Spring Roo does when a command is executed, and why it is important in the context of the application being developed.

Initially, you make a quick start with using Spring Roo through some simple recipes. Then you learn how Spring Roo simplifies creating the persistence layer of an enterprise application using JPA. You are introduced to the various roo commands to create JPA entities, create relationships between JPA entities, create integration tests using Spring TestContext framework, and so on. Following this, the book shows you how Spring Roo simplifies creating the web layer of an enterprise application using Spring Web MVC, Spring Web Flow, and how to create selenium tests for controller objects.

Subsequently, we focus on using Spring-BlazeDS, GWT, JSON, and so on. Spring Roo commands that are used to incorporate e-mail/messaging features into an enterprise application are demonstrated next. Finally, we wrap it up with some miscellaneous recipes that show how to extend Spring Roo via add-ons, incorporate security, create cloud-ready applications, remove Spring Roo from your enterprise application, and so on.

Publication date:
September 2011
Publisher
Packt
Pages
460
ISBN
9781849514583

 

Chapter 1. Getting Started with Spring Roo

In this chapter, we will cover the following topics:

  • Setting up Roo

  • Getting help and hints from Roo

  • Creating a Roo project

  • Importing a Roo project into Eclipse or IntelliJ IDEA IDE

  • Configuring logging

  • Viewing properties defined in a properties file

  • Managing properties defined in a properties file

  • Creating a Java class

  • Adding attributes to a Java class

  • Creating a Java interface

  • Referring to a type from the Roo shell

  • Creating application artifacts from Roo script

 

Introduction


Java provides an excellent platform for enterprise application development but has often been weighed down by productivity issues. For instance, if you want to develop a web application, then you need to learn a web framework, create JSPs or views, implement service layer, integrate services with a persistence framework, implement persistence logic, create configuration files for different application layers, write unit and integration tests, write build scripts, and so on. Phew! It seems like a lot of work to even create a simple web application that uses a standard set of Java frameworks. This is the reason why many organizations moved to platforms, which offer quick-start to developing simple or medium complexity applications. With the arrival of open source frameworks like Spring and Hibernate, Java platform received a big boost in terms of developer productivity and simplicity; it was still off the mark when it came to productivity levels compared to platforms like Ruby on Rails, until Spring Roo arrived.

Spring Roo is the next generation rapid application development tool for Java programming language. It is an open source tool, which comes under the umbrella of SpringSource (http://www.springsource.org/) projects. Applications developed using Spring Roo make use of the Spring programming model, which already has a proven track record of delivering portable, testable, and maintainable enterprise applications.

Spring Roo is an easy-to-use tool for rapidly developing Java enterprise applications using well-recognized frameworks such as Spring, Hibernate, AspectJ, Spring Web Flow, Spring Security, GWT, Flex, and so on. Spring Roo takes care of creating project structure for your enterprise application, adding support to use Maven for building and deploying the application, creating application architecture based on your choice of technologies, creating unit and integration tests based on your choice of testing framework, and so on. Spring Roo provides an interactive, intuitive, text-based interface through which you enter the details of your application in a step-by-step fashion to create a working application in minutes.

Note

When using Spring Roo, it's up to the enterprise application developer to choose the technology or framework to use in developing the application. For instance, you can choose Hibernate or OpenJPA for persistence and Spring Web Flow or GWT for the web layer.

So, what do you need to learn to develop applications using Spring Roo? As we will see shortly, you need to learn hardly anything to develop enterprise applications using Spring Roo. Spring Roo's key goal has been to utilize existing knowledge of enterprise developers and automate most of the tasks that a developer had to perform in a typical enterprise application development project. This results in increased developer productivity with nearly no learning curve. Isn't it exciting that you can rapidly develop Java enterprise applications using standard Java technologies without learning anything new?

Before we jump into using Spring Roo tool, let's have a look at the key benefits of using Spring Roo:

  • Improved enterprise developer's productivity: Spring Roo improves enterprise developer's productivity by auto-generating code based on instructions provided by developer or inferred from the code already generated by Spring Roo.

  • Productivity improvement throughout project lifecycle: Spring Roo not only gets you quickly started with the project but it also gives you productivity improvements over the lifetime of the project.

  • No extra layers of abstraction: Spring Roo doesn't attempt to hide implementation details from enterprise developers, making it easy for developers to understand the code and modify it as per their need.

  • No runtime dependency: If you develop applications using Spring Roo, at runtime your application code is only dependent on frameworks that you used for developing the application, nothing more, nothing less.

  • No vendor lock-in: At any time you decide to move away from using Spring Roo, you can use Eclipse IDE or STS (Spring Tool Suite—SourceSource's Eclipse flavor) to remove Spring Roo specific details from your application.

The following figures shows what you can do with Spring Roo and the benefits that you get:

The given figure shows that you can also use Spring Roo for creating proof of concepts, for creating prototypes, and for learning new technologies. With Spring Roo you can quickly create a working application in minutes, which makes it an ideal candidate for developing prototypes and creating proof of concepts. A developer can use Spring Roo to create a simple application using the technology that (s)he wants to learn and play around with it or go through the Roo-generated source code to quickly learn about the technology.

In this chapter, we will look at recipes that will help you get started with using Spring Roo for developing your enterprise application. The recipes in this chapter focus on demonstrating how you set up Roo, create a Roo project, create some of the project artifacts, get help and hints on various Roo commands from the Roo shell, and import Roo project in your favorite IDE. This chapter will set the stage for more advanced recipes that we will see in the later chapters of this book.

 

Setting up Roo


The first thing that you need to do to get started with using Spring Roo is to set up the Roo tool on your laptop or desktop.

In this recipe, we will look at how you can install Spring Roo and verify that it's ready to use.

Tip

What do I need to learn to effectively use Spring Roo?

If you are an experienced Java enterprise developer, then you hardly need to learn anything new to use Spring Roo. If you know how AspectJ ITDs (Inter-type Declarations) work, then it will be helpful to understand what Spring Roo does behind the scenes. As you go through the various recipes in this book, you will find enough details on how Spring Roo makes use of AspectJ ITDs.

Getting ready

As you are going to install Spring Roo, you first need to download Spring Roo ZIP archive from the official home page of Spring Roo(http://www.springsource.org/roo/start). Also, ensure that you have the following software installed on your machine:

How to do it...

To install Spring Roo, all you need to do is to follow the given steps:

  1. Unzip the downloaded Spring Roo ZIP archive into a directory. Once you have unzipped Spring Roo ZIP file, you will see the directory structure (excluding the cache directory) as shown in the following screenshot:

  2. Set the JAVA_HOME environment variable to point to the Java SE installation directory.

  3. Set the ROO_HOME environment variable to point to the Roo installation directory.

  4. If you are using Windows, add the ROO_HOME/bin directory to the PATH environment variable. If you are using Linux or Mac OS X, then create a symbolic link to the ROO_HOME/bin/roo.sh shell script.

  5. Roo installation isn't complete unless you verify it. So, create a ch01-recipe sub-directory in the C:\roo-cookbbook directory, open command prompt, and go to the ch01-recipe directory. Now, execute the roo.bat batch file, as shown in the following commands:

    Tip

    Downloading the example code

    You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

    C:\>cd roo-cookbbook
    C:\roo-cookbbook>cd ch01-recipe
    C:\roo-cookbbook\ch01-recipe>roo
        ____  ____  ____
       / __ \/ __ \/ __ \
      / /_/ / / / / / / /
     / _, _/ /_/ / /_/ /
    /_/ |_|\____/\____/    1.1.1.RELEASE [rev 156ccd6]
    
    
    Welcome to Spring Roo. For assistance press TAB or type "hint" then hit ENTER.
    ..
    roo>
    
  6. If you see the output as shown, it means you have successfully installed Spring Roo. You will notice that when you execute roo.bat or roo.sh, the command prompt changes to roo>. You are now ready to play with Spring Roo.

How it works...

Spring Roo is built on top of Apache Felix (http://felix.apache.org/site/index.html) OSGi container, which promotes modularity and dynamic assembly of applications. The bundle directory contains OSGi bundles that form part of Spring Roo release. These bundles provide core services required by Roo and add-ons that support code generation. When you first start Spring Roo by executing Roo batch file or shell script, then these bundles are installed and copied into the cache directory of your Spring Roo installation.

There's more...

Spring Roo comes with certain core services and base add-ons that are part of Spring Roo distribution. Core services like the Roo shell, file system monitor, bootstrap, and so on, provide the necessary infrastructure for the add-ons to perform their intended responsibility. Add-ons are at the heart of Spring Roo and they provide the code generation functionality. For instance, the e-mail add-on adds e-mail support and the JPA (Java Persistence API) add-on helps with setting up a JPA provider, creating JPA entities, their relationships, and so on.

As Roo add-ons are OSGi compliant, you can additionally create a custom add-on or download a third-party add-on and install it as part of your Spring Roo installation to extend Roo's functionality.

 

Using Spring Roo with Eclipse/STS


As Roo is a command-line driven tool, you may want to integrate it with a feature rich IDE like Eclipse or STS to simplify application development. If you are using STS, you don't need to worry about integrating Roo with it because support for Roo is built into STS. If you want to integrate Roo with Eclipse, you can install STS components in Eclipse, in the same way as you install any other Eclipse plugin.

If you are using any other IDE or you don't want to integrate your Eclipse IDE with Spring Roo, you can run Spring Roo in the background and use your favorite IDE to develop your enterprise application. As you make modifications to your enterprise application using your IDE, Spring Roo will work in the background to manage the enterprise application.

The following screenshot shows Spring Roo was started from inside Eclipse IDE. It shows that the roo> prompt is now displayed adjacent to a text box where you can enter your Roo commands:

If you compare the output shown in the given screenshot with the output that you saw earlier when you started the Roo shell from command prompt, you will notice that they are not the same. Really? Yes, in the case of Eclipse or STS, to use auto-completion (as suggested in the welcome text) feature of Roo commands, you need to use CTRL + SPACE instead of TAB.

See also

  • The next recipe, titled Getting help and hints from Roo, shows how Spring Roo provides context-sensitive hints on using the Roo shell and how to access help at any given time.

 

Getting help and hints from Roo


One of the key features of the Spring Roo shell is that it provides context-sensitive hints to the developers. The hints feature of Spring Roo provides step-by-step guidance on developing a working enterprise application in minutes. For instance, if you haven't created a Roo project in the directory from which you are running the Roo shell, issuing the hint command tells you how to go about creating a Roo project. If Roo finds that the directory from which the Roo shell is executing contains a Roo project but a JPA persistence provider is not set up yet, it suggests you set up a persistence provider (such as OpenJPA and Hibernate) for your project.

Tip

What is a Roo project?

A Roo project is nothing but a Java project whose source code consists of Java source files and .aj (AspectJ) files. If you decide to move away from Roo, you can easily do so because there is no runtime dependency of the generated code on any Roo libraries. Refer to the Removing Roo-specific details from your project recipe in Chapter 7 to see how to use IDEs like Eclipse and STS to remove Roo.

The help command provides a list of commands that are supported by a particular version of Spring Roo, accompanied with a short description of the purpose of the command. The commands listed by the help command are the only commands that you can execute from the Roo shell.

It is important to note that you may not be able to execute some of the Roo commands listed by help command, if they are not applicable to your Roo project. For instance, if you haven't set up a JPA persistence provider for your enterprise application, the Roo shell doesn't allow you to execute commands for creating JPA entities.

Getting ready

To execute the commands defined in this recipe, first create an empty directory from which you will start your Roo shell. For instance, you can create a sub-directory named ch01-recipe inside the cookbook-recipe directory in the C: drive. Go to the ch01-recipe directory and execute roo.bat batch file to start the Roo shell.

How to do it...

To get help and hints from Roo follow the given steps:

  1. To get help from Spring Roo, all you need to do is enter the help command in your Roo shell. But, we will do it a bit differently in our case. Instead of entering the complete command name, enter the letter h and press TAB (if you are using standalone Spring Roo installation) or CTRL + SPACE if you are using Spring Roo installed in Eclipse IDE or STS. You will get the following output from the Roo shell:

    roo> h
    help   hint
    roo> h
    

    As shown in the given code, the Roo shell provides the list of matching commands that it finds. In this case, it's help and hint. Now, enter he into the Roo shell and press TAB or CTRL + SPACE. You will notice that now the Roo shell automatically completes the command for you to reflect the matching help command.

    Once you enter the help command, you will get the list of commands supported by Spring Roo, shown as follows:

    roo> help
    .....
    * class - Creates a new Java class source file in any project path
    * interface - Creates a new Java interface source file in any project path
    * project - Creates a new project
    * quit - Exits the shell
    * version - Displays shell version
    .....
    

    As you can see, the help command provides a short description about all the commands supported by Spring Roo. For instance, it tells you that you can use the quit command to exit the Roo shell and the version command to know the version of Spring Roo that you are currently using.

  2. Now that you know how help command is useful, let's try out the hint command, shown as follows:

    roo> hint
    Welcome to Roo! We hope you enjoy your stay!
    Before you can use many features of Roo, you need to start a new project.
    To do this, type 'project' (without the quotes) and then hit TAB.
    Enter a --topLevelPackage like 'com.mycompany.projectname' (no quotes).
    When you've finished completing your --topLevelPackage, press ENTER.
    Your new project will then be created in the current working directory.
    ....
    

    As you can see from the given output, Spring Roo shows the hint on how to go about creating a project using the project command. We will make use of the hint command in later recipes to discover how it is useful in creating a fully functional project.

How it works...

As mentioned earlier, Spring Roo consists of core services and add-ons. Add-ons are meant for generating code based on commands executed by the developer. While executing commands like hint and help, Roo is not generating any code. You can say that these commands are processed by the core services and not by any Spring Roo add-on.

There's more...

Spring Roo also provides with the option to pass arguments to Roo commands, which is covered in the following section. Also when you execute a command from the Roo shell, it is recorded in a Roo script file, which is explained in the Log file for executed Roo commands section.

Passing arguments to Roo commands

Like most Roo commands, the help and hint commands accept arguments. Arguments are additional parameters that are passed to a Roo command to customize command behaviour. For instance, the help command accepts a command argument and the hint command accepts a topic argument.

Earlier, we saw that the help command provides high-level details about commands supported by Spring Roo. The command argument is used to specify the name of the command for which detailed help information is needed, including information about required and optional arguments that can be passed to the Roo command. Similarly, the topic argument of hint command provides detailed information on a particular topic. The command and hint arguments are optional arguments; Roo shell doesn't force you to specify them.

In most cases Roo expects you to specify arguments in the following format:

--<argument-name> <argument-value>

To simplify using the hint and help commands, Roo lets you specify arguments without un-necessary frills. For instance, you can enter the help project command to get help information on the project command or you can enter the hint jpa command to get hints related to JPA.

The following output from the Roo shell shows the results from executing the help project and hint jpa commands:

roo> help project

Keyword:                   project
Description:               Creates a new project
 Keyword:                  ** default **
Keyword:                  topLevelPackage
   Help:                   The uppermost package name (this becomes the <groupId> in Maven and also the '~' value when using Roo's shell)
Mandatory:              true
.....

roo> hint jpa
Roo requires the installation of a JPA provider and associated database.

Type 'persistence setup' and then hit TAB three times.
.....

As you can see from the given output, the help command gives the exact details about a command. For instance, the help project command suggests that the project command accepts a mandatory argument named topLevelPackage. The hint jpa command provides high-level details about the jpa topic.

So, the question arises, how do you find the topics on which hints are available? Well, you can find these topics from Roo by executing the hint topics command, shown as follows:

roo> hint topics

The following hints are available to help you use Roo:
general, start, jpa, entities, fields, relationships,
controllers, finders, eclipse, logging
Just type 'hint topic_name' (without quotes) to view a specific hint.

The given output suggests that Spring Roo provides hints on the following topics: jpa, entities, fields, relationships, and so on.

The help and hint commands are the most often used commands; it is recommended that you should use them as and when required while working with your Roo project.

Log file for executed Roo commands

Let's say that you created an enterprise application using Spring Roo consisting of Spring Web MVC and Hibernate frameworks. Additionally, you executed Roo commands to add e-mail and JMS message sending support to some of the classes that you created as part of your enterprise application. Now, let's say a similar project needs to be created in your organization, which makes use of Spring Web MVC, Hibernate frameworks, and requires e-mail and JMS message sending functionalities. You can either re-execute all the Roo commands (that you used in your earlier enterprise application) to create the new enterprise application, or you can simply execute the Roo script from the earlier enterprise application.

When you execute a command from the Roo shell, it is recorded in a Roo script file, named log.roo. You will notice that a log.roo script file is created in the ch01-recipe directory. The log.roo script contains the commands that you executed using the Roo shell and also the details of when you started the Roo shell or exited it. This feature of Spring Roo can be useful if you want to review the commands that you executed or if you want to execute the same set of commands using the script command of Spring Roo. In a moment you will see how to execute a Roo script file, in the Creating application artifacts from Roo script recipe of this chapter.

See also

  • The next recipe, Creating a Roo project shows how you can use the help command to discover the details of the project command, which is used for creating a Roo project.

 

Creating a Roo project


This is the first recipe in which you will see Spring Roo doing some real work to help you create a Java enterprise application. This recipe shows how to go about creating a Roo project using project command. The end result of following this recipe will be a project, which follows standard Maven directory structure. The project created in this recipe can be packaged as a JAR file because it doesn't have a web layer. In Chapter 4, Web Application Development with Spring Web MVC and Chapter 5, Web Application Development with GWT, Flex, and Spring Web Flow you will see how to create a web layer of an enterprise application using Spring Roo. The project that you will create in this recipe will act as a foundation for the rest of the recipes in this chapter.

Getting ready

The first thing that you need to do is to create an empty directory in which you are going to create your Roo project. Create a ch01-recipe sub-directory in the C:\roo-cookbbook directory, if you haven't created it yet. Start the Roo shell from the ch01-recipe directory by executing the Roo batch file or shell script, as shown here:

C:\roo-cookbook\ch01-recipe>roo

How to do it...

To create a Roo project, execute the project command from your Roo shell, shown as follows:

roo>project --topLevelPackage sample.roo.flightapp --java 6 --projectName flight-app

Created C:\roo-cookbook\ch01-recipe\pom.xml
.....
Created SRC_MAIN_RESOURCES\META-INF\spring\applicationContext.xml
Created SRC_MAIN_RESOURCES\log4j.properties

sample.roo.flightapp roo>

Notice the change in the Roo prompt after the execution of the project command. The change in prompt indicates that you are now working with a project whose top-level package is sample.roo.flightapp. If you start the Roo shell from a directory, which already contains a Roo project, then the Roo prompt will not change.

How it works...

The following table describes the purpose of each of the arguments passed to the project command:

Argument

Purpose

topLevelPackage

This is a Mandatory argument, which identifies the base or root package of your project. You will refer to this package frequently in your Roo commands using the tilde symbol (~). The value of this argument becomes the value of the <group-id> element in maven's pom.xml file.

java

This is an optional argument, which specifies the version of Java (must be 5, 6, or 7) with which the source and compiled classes of the Roo project should be compatible with. If unspecified, the Java version is auto-detected by Spring Roo.

projectName

This is an optional argument, which specifies the name of the project. The value of this argument becomes the value of <artifact-id> and <name> elements in maven's pom.xml file. If unspecified, the last part of the package name specified as the value of topLevelPackage argument is used. For instance, if the topLevelPackage argument value is sample.roo.flightapp, and the projectName argument is not specified, the value of projectName argument is assumed to be flightapp.

Tip

Use TAB or CTRL + SPACE regularly for discovering mandatory and optional attributes, and their pre-defined values

As it's hard to remember all the mandatory and optional attributes of different Roo commands, it's recommended that you use TAB (if you are using standalone Roo) or CTRL + SPACE (if you are using Roo from within Eclipse or STS) to use the auto-completion feature of Roo. Roo not only provides auto-completion of Roo commands (as we saw in an earlier recipe), but it also displays the mandatory arguments of a command when you press TAB or CTRL + SPACE. If you want to know about the optional arguments of a command, simply enter -- followed by TAB or CTRL + SPACE. To restrict users from entering any arbitrary value, a command argument may accept only a particular value from a set of pre-defined values for that argument. The pre-defined values are defined by the add-on responsible for processing the command. If an argument accepts a value from a set of pre-defined values by Roo, it is displayed when you press TAB or CTRL + SPACE.

Spring Roo distribution comes with a Maven add-on , which is responsible for processing the project command. There are more Roo commands that are processed by the Maven add-on, which you will see later in this book.

The output of project command shows that it creates directories with name SRC_MAIN_JAVA, SCR_MAIN_WEBAPP, and so on. These are logical names given to standard directories created by the Maven add-on. The following table shows the directories to which each of these names map in the case of the flight-app project:

Path value

Project directory

SRC_MAIN_JAVA

Refers to the root of the Java source directory, which contains application's Java sources: ch01-recipe\src\main\java.

SRC_MAIN_RESOURCES

The root of the directory, which contains resources (Spring's application context XML, database properties file, log4j properties file, persistence.xml file, and so on) required by the Java enterprise application: ch01-recipe\src\main\resources.

SRC_TEST_JAVA

The root of the Java source directory, which contains unit and integration tests: ch01-recipe\src\test\java.

SRC_TEST_RESOURCES

The root of the directory, which contains resources required during unit and integration testing: ch01-recipe\src\test\resources.

SRC_MAIN_WEBAPP

The web application directory, which contains web pages, images, style sheets, and web application configuration: ch01-recipe\src\main\webapp.

ROOT

Refers to the root directory of the project, which is ch01-recipe in case of flight-app project.

SPRING_CONFIG_ROOT

Refers to the directory, which contains Spring's application context XML file. In the context of flight-app project this refers to ch01-recipe\src\main\resources\META-INF\spring.

As evident from the execution of the project command, not only did it create a maven-ized project, it also created Spring's applicationContext.xml, maven's pom.xml file, and a log4j.properties file. The following XML code shows the contents of the applicationContext.xml file, which contains some interesting details:

<beans ..>

   <context:property-placeholder 
      location="classpath*:META-INF/spring/*.properties"/>

   <context:spring-configured/>

   <context:component-scan base-package="sample.roo.flightapp">
   <context:exclude-filter 
                  expression=".*_Roo_.*" type="regex"/>
   <context:exclude-filter expression=
      "org.springframework.stereotype.Controller"   
      type="annotation"/>
   </context:component-scan>
</beans>

The important inferences that we can derive from the content of applicationContext.xml are:

  • The definition of the <property-placeholder> element of Spring's context namespace indicates that you must put your properties files that contain configuration information for Spring beans, in the META-INF/spring directory so that they can be picked up by Spring's application context. In the next chapter, we will see how this is used by Roo-generated applications to read database properties from an external properties file.

  • The <spring-configured> element of Spring's context namespace specifies that objects that are annotated with @Configurable annotation are configured using Spring, even if they are created outside of the Spring container. The objects created outside the Spring container include objects that are created programmatically using the new operator or by reflection. We will see example usage of @Configurable annotation in Chapter 2, Persisting Objects Using JPA.

  • The <component-scan> element of Spring's context namespace specifies that Spring components (that is, components annotated with @Service, @Repository and @Component Spring annotations) found inside the sample.roo.flightapp package or its sub-packages are automatically registered with Spring's application context. Later in this chapter, we will use this feature to create a service class in the flight-app project, which is auto-registered with Spring's application context.

The other important artifact that was generated during the project creation is the pom.xml file that is used by maven. The following XML code shows how the argument values specified in the project command are used in creating the pom.xml file of the flight-app project:

<project >
   .....
   <groupId>sample.roo.flightapp</groupId>
   <artifactId>flight-app</artifactId>
   <packaging>jar</packaging>
   <version>0.1.0.BUILD-SNAPSHOT</version>
   <name>flight-app</name>
</project>

You may notice that the value of the <packaging> element is jar and not war. The reason for this lies with the fact that we haven't yet added a web layer to the flight-app application. We will see in Chapter 4, Web Application Development with Spring Web MVC and Chapter 5, Web Application Development with GWT, Flex, and Spring Web Flow how we go about creating a web application using Spring Roo.

The pom.xml additionally contains Maven plugins, which are available to Roo projects by default. The following table summarizes some of the important Maven plugins that are available to our newly created flight-app project:

Maven Plugin

Usage

IDEA plugin

You may use this plugin to convert the flight-app project into an IntelliJ IDEA project.

Eclipse plugin

You may use this plugin to convert the flight-app project into an Eclipse project.

AspectJ compiler plugin

This plugin weaves AspectJ aspects into your project classes. This plugin is used internally by Spring Roo. We will see the AspectJ compiler in action in Chapter 2.

Tomcat and Jetty plugins

You can use these plugins during development to run Tomcat or Jetty in embedded mode to test your web application.

There's more...

You won't always be starting a project from scratch, and you may find Spring Roo compelling enough (which you will, as we go through its various features) to use in your existing Spring-based Java projects. In such scenarios, you need to do the following:

  1. Convert your existing Spring-based project into a standard Maven project as created by Spring Roo's project command.

  2. Add the AspectJ compiler plugin to the pom.xml file of your project.

  3. Move bean definitions in your existing project to the applicationContext.xml file in META-INF/spring directory.

  4. Move the properties file used for configuring Spring beans to META-INF/spring/ directory.

There are other things you will need to do to convert your existing projects into a Roo project, which we will discuss in relevant recipes.

See also

  • The Configuring logging recipe discusses how to configure logging in Roo projects

  • Refer to the Creating a Java class and Create a Java interface recipes to find out how you can use Spring Roo to create classes/interfaces in your application

 

Importing a Roo project into Eclipse or IntelliJ IDEA IDE


As explained in the Setting up Roo recipe, you can either use STS or Eclipse with STS components installed to work with Roo projects. Alternatively, you can create necessary project files to import the Roo project into Eclipse or IntelliJ IDEA IDE (for working directly with Java sources and configuration files) and run the Spring Roo shell separately in standalone mode to execute Roo commands.

In this recipe, we look at how you can import a Roo project into Eclipse or IntelliJ IDEA by executing commands provided by Spring Roo.

Getting ready

Start the Roo shell from the C:\roo-cookbook\ch01-recipe directory, which contains the flight-app Roo project.

How to do it...

To import the Roo project into Eclipse or IntelliJ IDEA follow the given steps:

  1. To create Eclipse-specific project files, execute the perform eclipse command from the Roo shell, shown as follows:

    roo> perform eclipse
    

    Alternatively, you can use the perform command to execute the eclipse:eclipse Maven goal of the Maven Eclipse plugin, shown as follows:

    roo> perform command --mavenCommand eclipse:eclipse
    
  2. To create IntelliJ IDEA specific project files, use the perform command to execute the idea:idea Maven goal of the Maven IDEA plugin, shown as follows:

    roo> perform command --mavenCommand idea:idea
    

How it works...

The perform eclipse and perform command commands are processed by the Maven add-on of Spring Roo. The perform eclipse command generates Eclipse IDE specific configuration files, such as .project and .classpath files. Behind the scenes, the perform eclipse command executes the eclipse:eclipse goal of the Maven eclipse plugin.

The perform command is used to execute a Maven command. It accepts a single mandatory argument, mavenCommand , which identifies the Maven goal to execute.

Note

Maven IDEA and Eclipse plugins are configured in the pom.xml file by Spring Roo at the project creation time; you don't need to add them to your Roo project to use the commands shown in this recipe.

There's more...

If you are using any IDE other than STS, then ensure that you install AJDT (AspectJ Development Tools), as it gives better development experience when working with projects that make use of AspectJ aspects. For instance, when you open a Java source file in Eclipse IDE (that has AJDT installed), the Cross Reference tab shows the various AspectJ declarations that apply to the selected Java source file, and you can select these declarations to open the corresponding AspectJ ITD files.

See also

  • Refer to the Setting up Roo recipe to know how to use STS or Eclipse (with STS components) for developing with Spring Roo

  • Refer to the Removing Roo-specific details from your project recipe in Chapter 7, Developing Add-ons and Removing Roo from Projects to see how you can convert your Roo project into a normal Java project

 

Configuring logging


In the Creating a Roo project recipe, you saw that when you create a new project, a log4j.properties file is automatically created with default logging configuration. In most real projects, you'd like to customize the default logging configuration. By default, the log4j.properties file configures root logger at ERROR level and logging is not enabled for the project.

In this recipe, we will look at the logging setup command to modify the logging configuration.

Getting ready

Start the Roo shell from the C:\roo-cookbook\ch01-recipe directory, which contains the flight-app Roo project.

How to do it...

Using the logging setup command you can specify the logging level and the package to which it applies, as shown in the following steps:

  1. The following logging setup commands are used to change the logging level of rootLogger to DEBUG (which is ERROR by default) and enable DEBUG level logging for all classes in the flight-app application:

    roo> logging setup --level DEBUG --package ROOT
    Updated SRC_MAIN_RESOURCES\log4j.properties
    
    roo> logging setup --level DEBUG --package PROJECT
    Updated SRC_MAIN_RESOURCES\log4j.properties
    

    As the output from the command execution suggests, some changes have been made by Roo to the log4j.properties file.

    Tip

    Keep an eye on the output of a command

    When a Roo command is executed, it displays information about what files and directories have been created or which files have been updated. This can be helpful if you want to check the code that is generated on execution of a command.

  2. To confirm that the changes have been made to the log4j.properties, you can either view it directly by opening the file or you can use the properties list command (explained in the next recipe).

How it works...

The logging setup command is processed by the Logging add-on of Spring Roo. The following table describes the arguments that the logging setup command accepts:

Argument

Purpose

level

This is a mandatory argument, which identifies the logging level. It can only take one of the pre-defined values, like DEBUG, ERROR, INFO, and so on.

package

This is an optional argument, which specifies the package to which the logging level applies. It can only take one of the pre-defined values, such as PROJECT, ALL_SPRING, PERSISTENCE, and so on.

There's more...

As of Spring Roo 1.1.3, using the logging setup command you can't specify a custom package name as the value of the package argument; therefore, you can set a custom package name either by using the properties set command (explained later in this chapter) or by directly editing the log4j.properties file.

See also

  • The Viewing properties defined in a properties file, Removing a property defined in a properties file, and Adding properties to a properties file recipes show how you can manage properties files in your Roo project.

 

Viewing properties defined in a properties file


If your project contain properties files, you may want to view their content. For instance, when we created the flight-app Roo project earlier, a log4j.properties file containing logging configuration was also created. In this recipe, we will look at the properties list command to view the contents of the log4j.properties file.

Getting ready

Start the Roo shell from C:\roo-cookbook\ch01-recipe directory, which contains the flight-app Roo project.

How to do it...

To view the contents of a properties file, the properties list command requires a path to the properties file and its name. The following properties list command displays the contents of the log4j.properties file:

roo> properties list --name log4j.properties --path SRC_MAIN_RESOURCES

log4j.appender.R = org.apache.log4j.RollingFileAppender
log4j.appender.R.File = application.log
...
log4j.logger.sample.roo.flightapp = DEBUG
log4j.rootLogger = DEBUG, stdout

How it works...

The Properties file add-on is responsible for processing the properties list command. The following table describes the arguments it accepts:

Argument

Purpose

path

It is a mandatory argument that identifies a path to the properties file. It only accepts pre-defined values like ROOT, SPRING_CONFIG_ROOT, SCR_MAIN_WEBAPP, and so on.

name

It is a mandatory argument that specifies the name of the properties file whose content you want to view.

See also

  • The next recipe, Managing properties defined in a properties file, shows how you can add, remove, and modify properties defined in properties files in your Roo project.

 

Managing properties defined in a properties file


In this recipe, we look at Roo commands, which you can use to add, remove, and modify properties defined in a properties file. We will use the log4j.properties file of the flight-app project to demonstrate the use of commands.

The following table shows the properties that we will add, modify, and remove from the log4j.properties file:

Property

Action

log4j.appender.R.File = application.log

Modified to log4j.appender.R.File = flightapp.log

log4j.rootLogger = debug, stdout

Modified to log4j.rootLogger = ERROR

log4j.appender.stdout = org.apache.log4j.ConsoleAppender

Removed from log4j.properties

log4j.logger.sample.roo.flightapp.service = ERROR

Added to log4j.properties

Getting ready

Start the Roo shell from the C:\roo-cookbook\ch01-recipe directory, which contains the flight-app Roo project.

How to do it...

To manage the properties defined in a properties file follow the given steps:

  1. The properties set command is used to modify properties shown as follows:

    roo> properties set --name log4j.properties --path SRC_MAIN_RESOURCES --key log4j.appender.R.File --value flightapp.log
    .....
    roo> properties set --name log4j.properties --path SRC_MAIN_RESOURCES --key log4j.rootLogger --value ERROR
    
  2. The properties remove command is used to remove properties, shown as follows:

    roo> properties remove --name log4j.properties --path SRC_MAIN_RESOURCES --key log4j.appender.stdout
    
  3. The properties set can also be used to add a new property, shown as follows:

    roo> properties set --name log4j.properties --path SRC_MAIN_RESOURCES --key log4j.logger.sample.roo.flightapp.service --value DEBUG
    

How it works...

Like the properties list command, the properties set and properties remove commands are provided by Properties file add-on . The following table describes the arguments that both the properties set and properties remove commands accept:

Argument

Purpose

path

It is a mandatory argument that identifies a path to the properties file. Refer to the Viewing properties defined in a properties file and Creating a Roo project recipes for details on the values it can accept.

name

It is a mandatory argument that specifies the name of the properties file whose property you want to remove

key

It is a mandatory argument that specifies the key of the property that you want to remove from the properties file.

The properties set command accepts all the arguments that the properties remove command accepts. Additionally, it accepts a mandatory argument, value, which specifies a value of the property being set by the properties set command. If a matching property is found in the properties file, the existing property is updated with the new value. If no matching property is found, a new property is added to the properties file.

There's more...

You can also change the properties file using your favorite IDE. If you are creating a new Roo project which acts as a template for creating other projects, using properties commands to add, modify, and remove properties from a properties file can be valuable.

If you want to modify logging configuration, you should first consider using the logging setup command (explained earlier in the Configuring logging recipe). If you want to modify database properties, you should use database commands (explained in the Managing database configuration properties recipe in Chapter 2, Persisting Objects Using JPA).

See also

  • The Configuring logging recipe explains how to configure logging using Spring Roo commands

  • The Managing database configuration properties recipe explains how to configure database properties using Spring Roo commands

 

Creating a Java class


You can create Java classes in your Roo project, either by using the IDE of your choice or by using the class command. If you create a class using Roo, boilerplate code (which includes toString , and get and setter methods for attributes) is generated automatically and managed by Spring Roo, and is kept in a separate AspectJ ITD file.

Getting ready

Start the Roo shell from the C:\roo-cookbook\ch01-recipe directory, which contains the flight-app Roo project.

How to do it...

You can create a Java class using the class command, as shown here:

roo> class --class sample.roo.flightapp.service.FlightService --rooAnnotations

Created SRC_MAIN_JAVA\sample\roo\flightapp\service
Created SRC_MAIN_JAVA\sample\roo\flightapp\service\FlightService.java
Created SRC_MAIN_JAVA\sample\roo\flightapp\service\FlightService_Roo_Serializable.aj

~.service.FlightService roo>

When the class command is executed, notice that the Roo prompt changes to refer to the newly created Java class. In the next recipe, titled Adding fields to a Java class, we will see how the changed Roo prompt simplifies performing commands on the referred class. Also, notice that the service directory is automatically created by Spring Roo, if it doesn't exist.

Tip

Some command arguments, like rooAnnotations, act as a flag for the command processor, and you don't need to specify their value. Simply specifying them as part of the command means that the value of the argument is true or yes.

How it works...

The class command accepts the arguments listed in the following table:

Argument

Purpose

class

It is a mandatory argument that identifies the fully-qualified name of the Java class that you want to create. You can either specify the fully-qualified class name using the tilde symbol '~' or you can use the TAB (or CTRL + SPACE) multiple times to let Spring Roo complete the package name for you.

The '~' symbol refers to the top-level package of the Roo project. For instance, in flight-app project, it refers to sample.roo.flightapp package. You can use this symbol to specify the package (relative to top-level package) in which you want to create your Java class.

rooAnnotations

It is an optional argument that specifies the common Roo annotations, such as @RooJavaBean, @RooToString, and @RooSerializable, which are added to the generated Java class. If unspecified, these annotations are not added to the generated Java class.

path

It is an optional argument that specifies the path to the source directory in which the class is created. By default, the path is SRC_MAIN_JAVA.

extends

It is an optional argument that specifies the fully-qualified name of the class, which the Java class extends. You can use this argument to create a class which extends from a superclass.

abstract

It is an optional argument that indicates whether the class is an abstract or concrete class. You can use this argument to create an abstract class.

permitReservedWords

It is an optional argument that indicates whether Roo should allow creating a class whose name is a reserved word. By default, Roo doesn't allow creating Java classes whose name uses reserved words. For instance, by default you cannot create a class named New.

As evident from the list of arguments accepted by the class command, Spring Roo doesn't provide any argument to let you specify the interface(s) that the generated Java class implements. If you want your Java class to implement one or more interfaces, you need to manually modify your class definition.

As the output from class command suggests, apart from FlightService.java, Roo creates a FlightService_Roo_Serializable.aj file—an AspectJ ITD that makes the FlightService class implement java.io.Serializable interface.

The AspectJ ITDs generated by Roo have the following naming convention:

<java-class-name>_Roo_<add-on-name>.aj

Where <java-class-name> is the name of the Java class to which the AspectJ ITD applies.

<add-on-name> is the name of Spring Roo add-on responsible for managing the AspectJ ITD

The *_Roo_*.aj files are managed by Roo and you should not directly modify or delete them.

The following code shows how the FlightService.java file generates the FlightService class using the class command:

package sample.roo.flightapp.service;

import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.tostring.RooToString;
import org.springframework.roo.addon.serializable.RooSerializable;

@RooJavaBean
@RooToString
@RooSerializable
public class FlightService { }

In the given code, Roo annotations were added to the generated FlightService class because we specified the rooAnnotations argument in the class command.

To simplify debugging, developers commonly override the toString method of the java.lang.Object class to output a string containing the value of all the attributes of the class. With Spring Roo, you are relieved of this task because if your class is annotated with @RooToString annotation, Spring Roo takes care of creating and updating the toString method as you add, modify, or remove attributes from your Java class.

When you add an attribute to your FlightService class, Roo creates a FlightService_Roo_ToString.aj—an AspectJ ITD that adds the toString method to the FlightService class, and a FlightService_Roo_JavaBean.aj—an AspectJ ITD that adds getters and setters methods for the attributes defined in the FlightService class. The creation of these aspects is triggered by the presence of @RooToString and @RooJavaBean annotations in the FlightService class.

To see these two ITD files, add the following attribute to FlightService class:

private String origin;

If your Roo shell is running, as soon as you save the FlightService class, Roo will generate a FlightService_Roo_ToString.aj file and a FlightService_Roo_JavaBean.aj file in the same package as the FlightService class. If you observe the Roo shell, you will find that Roo reports that it has created a FlightService_Roo_ToString.aj and FlightService_Roo_JavaBean.aj files, as shown here:

Created SRC_MAIN_JAVA\sample\roo\flightapp\service\
FlightService_Roo_ToString.aj

Created SRC_MAIN_JAVA\sample\roo\flightapp\service\
FlightService_Roo_JavaBean.aj

The following code shows how FlightService_Roo_ToString.aj AspectJ ITD adds the toString method to the FlightService class:

package sample.roo.flightapp.service;

privileged aspect FlightService_Roo_ToString
{
    
    public String FlightService.toString()
   {
      StringBuilder sb = new StringBuilder();
      sb.append("Origin: ")
      .append(getOrigin());
      return sb.toString();
   }
}

The given code shows that FlightService_Roo_ToString is a privileged aspect, that is, it can access even private members of other aspects and classes. The declaration, public String FlightSerivce.toString(), adds a public toString method to the FlightService class that accepts no arguments and returns a String. Everything inside the curly-braces is the implementation of the toString method. Each declaration in an AspectJ ITD file identifies the target of that declaration. In the code, FlightService in the declaration means that the FlightService class is the target; therefore, it will add the toString method to the FlightService class. In the Adding fields to a Java class recipe, we will see how the toString method is automatically updated by Spring Roo when you add more attributes to the FlightService class.

The following figure summarizes how the FlightService_Roo_ToString.aj file in the previous listing declares adding the toString method to the Flight class:

Note

In Spring Roo, AspectJ ITDs are responsible for adding fields, methods, and constructors to Java classes and to make them implement interfaces or extend from a superclass. Spring Roo is responsible for managing these ITDs and you should not directly modify or delete them.

The following code shows the FlightService_Roo_JavaBean.aj AspectJ ITD file:

privileged aspect FlightService_Roo_JavaBean
{
      
  public String FlightService.getOrigin()
   {
      return this.origin;
   }
    
  public void FlightService.setOrigin
   (String origin)
   {
      this.origin = origin;
   }
}

The given code shows that FlightService_Roo_JavaBean.aj is also a privileged aspect and it introduces two methods into the FlightService class: getOrigin and setOrigin, to get and set the value of the origin attribute.

The FlightService_Roo_Serializable.aj AspectJ ITD defines that the FlightService class implements the java.io.Serializable interface, as shown here:

package sample.roo.flightapp.service;

import java.io.Serializable;

privileged aspect FlightService_Roo_Serializable
{
    
   declare parents: FlightService implements Serializable;
    
  private static final long FlightService.serialVersionUID 
   = 5059552858884348572L
}

In the given code, the declare parents: FlightService implements Serializable statement declares that the FlightService class implements the java.io.Serializable interface. The following figure summarizes what this declaration means:

The statement private static final long FlightService.serialVersionUID = 5059552858884348572L, adds a serialVersionUID field (it's the field which you define if your class implements the Serializable interface) to the FlightService class that contains it.

There's more...

If you want Roo to manage the creation of the toString method and getter and setter methods for attributes of the class, it is recommended that you use the rooAnnotations argument in the class command.

Note

Roo annotations have source-level retention, which means that your application is not dependent on Roo annotations at runtime.

 

Moving existing Spring projects to use Spring Roo


If you are moving your existing Spring-based project to Roo, you can make out from this recipe that you should do the following:

  1. Remove the toString method and add the @RooToString annotation to all your existing classes.

  2. Remove the implementation of Serializable interfaces from classes and instead annotate the classes with the @RooSerializable annotation.

  3. Remove getters and setters methods from your Java classes and instead annotate the classes with the @RooJavaBean annotation.

Tip

Registering the service class with Spring's application context

Using Spring Roo you can't create a service class, which is automatically registered with Spring's application context; therefore, if you want your service class to be auto-registered, then annotate it with the @Service annotation. The service class will be registered with Spring's application context as long as it is inside the top-level directory (for more information refer to the <component-scan> element, described in the Creating a Roo project recipe).

@RooToString—customizing the name of the toString method

We saw that using the @RooToString annotation creates a method named toString in the corresponding AspectJ ITD file. You can use the toStringMethod attribute of the @RooToString annotation to specify a custom name for the toString method, as shown here:

@RooToString(toStringMethod = "myTostring")
public class MyCustomClass { private String myAttr; }

In the given code, the toStringMethod attribute specifies myToString as the name of the method to act as the toString method for the MyCustomClass. The ITD file corresponding to the @RooToString annotation: MyCustomClass_Roo_ToString.aj will now create a method similar to toString but with the name myToString, as shown here:

privileged aspect MyCustomClass_Roo_ToString
{
   public String MyCustomClass.mytostring ()
   {
      StringBuilder sb = new StringBuilder();
      sb.append("MyAttr: " ).append(getMyAttr());
      return sb.toString();
   }
}

@RooToString—excluding properties from the toString method

In some cases, you may want to restrict properties from being part of the auto-generated toString method. The @RooToString annotation provides an excludeFields attribute, which lets you specify an array of attributes that should be excluded from the auto-generated toString method, as shown here:

@RooToString(excludeFields={"someAttribute"})
public class MyCustomClass { .. }

In this code, the @RooToString annotation instructs that the toString method of the MyCustomClass class must not include the someAttribute property.

See also

  • The Adding attributes to a Java class recipe explains how you can add attributes to a Java class using roo

  • The Creating a Java interface recipe explains how you can create a Java interface from the Roo shell

 

Adding attributes to a Java class


You can add attributes to your Java classes in your Roo project, either from your IDE or by using the field commands of Spring Roo. There are advantages in adding attributes using Roo as opposed to using an IDE, which we will see in this recipe. The following table shows the name and type of attributes that we will add to a Passenger class in the package sample.roo.flightapp.domain of the flight-app project:

Field name

Type

firstName

java.lang.String

lastName

java.lang.String

age

java.lang.Integer

address

sample.roo.flightapp.domain.Address

Getting ready

Start the Roo shell from the C:\roo-cookbook\ch01-recipe directory, which contains the flight-app project.

How to do it...

Roo provides field commands, which you can use to add different types of fields in your Java class, shown as follows:

  1. Create an Address class, which is an attribute type in the Passenger class, as shown here:

    roo> class --class ~.domain.Address --rooAnnotations
    
  2. Create a Passenger class, to which we want to add attributes using the field commands, as shown here:

    sample.roo.flightapp.domain.Address roo> class --class ~.domain.Passenger --rooAnnotations
    
  3. Add firstName and lastName attributes to the Passenger class using field string command, shown as follows:

    sample.roo.flightapp.domain.Passenger roo> field string --fieldName firstName
    
    Updated ..Passenger.java
    Created ..Passenger_Roo_JavaBean.aj
    Created ..Passenger_Roo_ToString.aj
    
    .. roo> field string --fieldName lastName
    
    Updated ..Passenger.java
    Updated ..Passenger_Roo_JavaBean.aj
    Updated ..Passenger_Roo_ToString.aj
    
  4. Add an age attribute to the Passenger class, using the field number command, shown as follows:

    .. roo> field number --fieldName age --type java.lang.Integer
    
    Updated ..Passenger.java
    Updated ..Passenger_Roo_JavaBean.aj
    Updated ..Passenger_Roo_ToString.aj
    
  5. Add an address attribute of type Address to the Passenger class, using the field other command, shown as follows:

    .. roo> field other --fieldName address --type sample.roo.flightapp.domain.Address
    
    Updated ..Passenger.java
    Updated ..Passenger_Roo_JavaBean.aj
    Updated ..Passenger_Roo_ToString.aj
    

The given output for each of these commands shows that when an attribute is added to the Passenger class for the first time, the Passenger_Roo_JavaBean.aj and Passenger_Roo_ToString.aj files are created. You may notice that every time you add an attribute, the Passenger_Roo_JavaBean.aj and Passenger_Roo_ToString.aj AspectJ ITD files are also updated.

How it works...

Spring Roo provides multiple field commands for adding different types of attributes to the Java class. For instance, field string is for adding a String type field, field date is for adding a java.util.Date or java.util.Calendar type field, field other is for adding a field of custom Java type, and so on.

Note

Some of the field commands, like field set and field reference, apply only to JPA entities, and are therefore not applicable to every Java class that you create in your Roo project. Also, field commands accept certain arguments, which make sense only if the target Java class is a JPA entity. We will discuss JPA entity specific field commands in Chapter 2.

The field string, field other, and field number commands accept the name argument, which identifies the name of the attribute to be added to the Java class. The field other and field number also require the type of the attribute.

The following code shows Passenger_Roo_JavaBean.aj AspectJ ITD, which was modified by Spring Roo when we added fields to the Passenger class:

privileged aspect Passenger_Roo_JavaBean
{
   public String Passenger.getFirstName()
   {
      return this.firstName;
   }
   public void Passenger.setFirstName(String firstName)
   {
      this.firstName = firstName;
   }
...
}

The given code shows that Passenger_Roo_JavaBean.aj was updated by Spring Roo to introduce getter and setter methods for each of the fields added to Passenger class. This was possible because of the presence of @RooJavaBean annotation in the Passenger class.

The following code shows Passenger_Roo_ToString.aj AspectJ ITD, which was also modified by Spring Roo when fields were added to the Passenger class:

privileged aspect Passenger_Roo_ToString
{
   public String Passenger.toString()
   {
      StringBuilder sb = new StringBuilder();
      sb.append("FirstName:").append(getFirstName()).append(",");
      sb.append("LastName: ").append(getLastName()).append(", ");
      sb.append("Age: ").append(getAge()).append(", ");
      sb.append("Address: ").append(getAddress());
      return sb.toString();
   }
}

As the given code suggests, it introduces a toString method to the Passenger class, which returns a concatenated String containing the value of each of its attribute. This was possible because the Passenger class was annotated with the @RooToString annotation.

Tip

What if I add an attribute using IDE?

Spring Roo actively monitors changes to classes that are annotated with Roo annotations, and any change to classes triggers Spring Roo to update the corresponding AspectJ ITD files. So, it doesn't matter whether you add attributes to your Java class using Roo shell or an IDE.

The following figure shows how Spring Roo manages AspectJ ITD files:

The given figure shows that when you start the Spring Roo shell from a directory, it actively monitors the Java classes in the file system that are annotated with Roo annotations (for example @RooToString, @RooJavaBean, and so on). When any of these Java classes are modified using an IDE or any other editor, Spring Roo checks if the AspectJ ITD files (which follow the naming convention *_Roo_*.aj, as explained earlier) corresponding to the Java classes are in sync with the Java classes. If they are not, it updates the AspectJ ITD files accordingly. Spring Roo makes use of add-ons to make modifications to the AspectJ ITD files.

There's more...

This recipe showed that if you want Roo to automatically generate a toString method and getter and setter methods for all the attributes, then annotate your class with @RooToString and @RooJavaBean annotations.

Tip

What if I add an attribute when Spring Roo is not running?

When you start Roo shell, it checks if AspectJ ITDs are in sync with the corresponding Java classes. If there are differences, then Roo updates the AspectJ ITD files to reflect the current state of the Java class. At this time Roo may even remove an ITD file if it finds that it is no longer required. For instance, if you remove all the attributes from Passenger class, then the corresponding Passenger_Roo_JavaBean.aj and Passenger_Roo_ToString.aj files are automatically removed by Roo.

Spring Roo doesn't provide commands to remove or modify an attribute. So, if you want to remove or modify an existing attribute of a Java class, you can do so using your IDE. Spring Roo will take care of removing or modifying the attribute in corresponding AspectJ ITD files.

@RooJavaBean—controlling the generation of getter and setter methods

We saw that using @RooJavaBean annotation introduces getter and setter methods for all the fields in a class. In some cases, you may want to control the generation of these getter and setter methods. @RooJavaBean allows you to do so using the gettersByDefault and settersByDefault attributes. These attributes specify whether getter and setter methods should be generated by default or not. The default value of these attributes is true, which means the @RooJavaBean annotation will create getter and setter methods in the corresponding *_Roo_JavaBean.aj ITD for all the fields defined in the class.

If you specify the value of both gettersByDefault and settersByDefault elements as false, then Spring Roo deletes the corresponding AspectJ ITD file.

See also

  • The Creating a Java interface recipe shows how to create a Java interface using Spring Roo

  • The Adding fields to persistent entities recipe of Chapter 2, Persisting Objects Using JPA shows the additional arguments that are available in field commands

 

Creating a Java interface


You can use Spring Roo's interface command or an IDE to create a Java interface. In this recipe, we will see how we can create an interface named FlightServiceIntf.

Getting ready

Start the Roo shell from the C:\roo-cookbook\ch01-recipe directory, which contains the flight-app Roo project.

How to do it...

Spring Roo provides the interface command to create a Java interface, as shown here:

roo> interface --class sample.roo.flightapp.service.FlightServiceIntf

Created SRC_MAIN_JAVA\sample\roo\flightapp\service\FlightServiceIntf.java

sample.roo.flightapp.service.FlightServiceIntf roo>

How it works...

The following table describes the arguments that the interface command accepts:

Argument

Purpose

class

It is a mandatory argument, which specifies the fully-qualified name of the Java interface.

path

It is an optional argument, which identifies the directory in which to create the interface, default being SCR_MAIN_JAVA.

permitReservedWords

It is an optional argument, which instructs Spring Roo to allow reserved words in the name of Java interface.

There's more...

Using Spring Roo you can't add constants or declare methods in your Java interface. To add constants or methods, you need to use your IDE. You may have noticed that the rooAnnotations argument is not available for the interface command; therefore, you can safely assume that Spring Roo doesn't generate any code corresponding to a Java interface when you make modifications to it.

See also

  • The Creating a Java class recipe shows how to create a Java class using Spring Roo

 

Referring to a type from the Roo shell


In some scenarios, you may want to set the focus of your commands to a particular Java type. For instance, you may want the Roo shell to execute field commands on a particular Java type, so that you don't need to specify the class argument in your field commands.

Getting ready

Start the Roo shell from the C:\roo-cookbook\ch01-recipe directory, which contains the flight-app Roo project.

How to do it...

Spring Roo provides a focus command, which lets you change the target of your commands to a different Java type. The following sequence of steps shows how we can use the focus command to switch from one type to another:

  1. Execute the following focus command to specify that you want to work with the flight-app project. This will change the Roo prompt to reflect the top-level package name of Roo project:

    roo> focus --class ~
    
  2. Create FlightDesc class using the class command. Use ~ to denote that you are specifying the package name for the class with respect to the top-level package of the project. This will change the Roo prompt to refer to the FlightDesc type, shown as follows:

    sample.roo.Flightapp roo> class --class  ~.domain.FlightDesc --rooAnnotations
    
    Created SRC_MAIN_JAVA\sample\roo\flightapp\domain\FlightDesc.java
    
  3. Create a Flight class using the class command. This will change the Roo prompt from FlightDesc type to refer to the newly created Flight type, as shown here:

    ~.domain.FlightDesc roo> class --class ~.domain.Flight --rooAnnotations
    
    Created SRC_MAIN_JAVA\sample\roo\flightapp\domain\Flight.java
    
  4. Use a focus command to switch to the FlightDesc type. This will change the Roo prompt from referring to Flight type to FlightDesc type, as shown here:

    ~.domain.Flight roo> focus --class ~.domain.FlightDesc
    
  5. Add from_city and to_city attributes to the FlightDesc class as shown here. As the currently referred type by Roo prompt is FlightDesc, you don't need to specify the class argument:

    ~.domain.FlightDesc roo> field string from_city
    ~.domain.FlightDesc roo> field string to_city
    
  6. Without changing focus to the Flight class, add a flight_Id attribute to the Flight class by using the field command along with the class argument, as shown here. The class argument specifies that the target of the command is the Flight class and not the currently referred FlightDesc class:

    ~.domain.FlightDesc roo> field number --fieldName flight_Id --type java.lang.Integer --class ~.domain.Flight
    

How it works...

The class argument of the focus command lets you specify the fully-qualified name of the Java type with which you want to work. The ~ symbol is used to indicate the top-level package of the Roo project that you specified during creation of the Roo project.

Tip

The use of the ~ symbol simplifies providing the value of any argument that expects a fully-qualified name of a Java type in your Roo project.

There's more...

The use of the focus command is mainly to simplify writing commands targeting a particular Java type. If you don't want to use the focus command in a situation, then you can always use the class argument of the command to specify the target Java type of the command.

See also

  • The Creating a Java class recipe shows how to create a Java class using Spring Roo

  • The Adding attributes to a Java class recipe shows how to add attributes to a Java class using Spring Roo

 

Creating application artifacts from Roo script


In some scenarios, you may want to generate complete enterprise application skeleton by feeding a set of Roo commands to Spring Roo from a text file. To address such scenarios Spring Roo provides the script command, which allows you to execute commands contained in a text file. The convention is to name the script file containing commands with a .roo extension.

Note

Roo script is nothing but a text file containing Roo commands. The commands are executed in the order they appear in the text file.

In this recipe, we look at how we can execute the commands contained in a ch01.roo text file that accompanies this book. The ch01.roo file contains commands, which let's you create a fresh flight-app project.

Getting ready

If your Roo shell is still open, then exit it and remove all the files from the C:\roo-cookbook\ch01-recipe directory. Download the ch01.roo file from the book's website and copy it to C:\roo-cookbook\ch01-recipe. Start the Roo shell from the C:\roo-cookbook\ch01-recipe directory.

How to do it...

To create the application skeleton execute the script command, by specifying the file containing Roo commands, as shown here:

roo>script --file ch01.roo --lineNumbers

How it works...

The script command accepts the following arguments:

Argument

Purpose

file

It is a mandatory argument, which specifies the name of the file that contains Roo commands

lineNumbers

It is an optional argument that instructs the Roo shell to print the line numbers of the command being executed from the file

There's more...

One of the features that you will not find in Spring Roo is to revert the execution of a previous command. For instance, if you added a field using the field command and now you want to rollback the changes it made, then it is not possible. If you have mistakenly executed a Roo command, you can remove it from the log.roo file and re-execute the commands in log.roo using the script command.

If a Roo command fails for some reason, it is commented out in the log.roo file. So, you don't need to worry about removing commands that failed execution from your log.roo file.

See also

  • The Setting up Roo recipe show how you can get started with Spring Roo.

About the Author

  • Ashish Sarin

    Ashish Sarin has more than 11 years of experience architecting and developing web applications and portals using Java EE and the Portlets API. He has authored many articles on portlets and rich internet applications using Spring, Liferay, DWR, DOJO, JSF, and Spring Portlet MVC. He is also the author of Portlets in Action published by Manning Publications.

    Browse publications by this author
Book Title
Unlock this book and the full library for FREE
Start free trial