跳至主要内容

Create a Spring Project with Roo

Spring Roo is a rapid scollad tool brought by SpringSource, which can help you to create a data centered project in several minutes.

Assumption

I assume you are familiar with Apache Maven and Eclipse IDE. I also assume you have installed the latest Oracle JDK 7 in your local system.

Install Spring Roo

Download Spring Roo from SpringSource, and extract the file into your local disk. Add /bin to your system PATH environment variable.
For Linux user,
export PATH=$PATH:/bin (Linux)
For Windows user,
set PATH=%PATH%;/bin (Windows)

Create a project

Create a new folder as the new project root folder.
Open your system terminal, and enter the new created folder. Run roo command, it will launch the Roo console and display the Roo welcome message.
    ____  ____  ____
   / __ \/ __ \/ __ \
  / /_/ / / / / / / /
 / _, _/ /_/ / /_/ /
/_/ |_|\____/\____/    1.2.3.RELEASE [rev 7fd62b6]


Welcome to Spring Roo. For assistance press TAB or type "hint" then hit ENTER.
Type project and press TAB it will fetch all the options of project addon command. You must specify a topLevelPackage parameter option to the project command.
project --topLevelPackage com.hantsylabs.example.spring.conference
It will generate a Maven based web project. By default the specified package name will be the groupId of the created project, and the last part of the package name will be the artifactId.
Note: Anytime you can type hint command in the Roo console to get some suggestions for the next steps. When you are typing any command, you can press TAB to get the proposals for the optional commands or the available options of the specified command. For example, type pro and press TAB it will complete project automatically for you and press TAB again, it will provide all options of project command for you. When you append --topLevel to the project command and press TAB, it will complete the option --topLevelPackage for you.

Setup persistence

After you created the project, Roo will provide some suggestions to guide you to setup jpa for this project.
Type jpa setup and press TAB, it will provides all options of jpa setup command, you have to specify --database and --provider.
Append --database and hint TAB, it will display all databases supported in Spring Roo for you.
roo> persistence setup --database

DATABASE_DOT_COM        DB2_400                 DB2_EXPRESS_C
DERBY_CLIENT            DERBY_EMBEDDED          FIREBIRD
GOOGLE_APP_ENGINE       H2_IN_MEMORY            HYPERSONIC_IN_MEMORY
HYPERSONIC_PERSISTENT   MSSQL                   MYSQL
ORACLE                  POSTGRES                SYBASE
In this project HYPERSONIC_IN_MEMORY(a embedded HSQL database) is selected as the datastore.
After database is selected, press TAB in the current command line, it will guide you to add --provider options.
roo> persistence setup --database HYPERSONIC_IN_MEMORY --provider

DATANUCLEUS   ECLIPSELINK   HIBERNATE     OPENJPA
In this demo project, we choose Hibernate as JPA provider.
Note: Anytime you can get useful help for the next steps by press TAB when you are in a command line.
After the JPA provider is selected, the related configuration will be generated and the Maven dependencies will be added into pom.xml file.
Roo will resolve the dependencies for you automatically.

Create an Entity

Roo provides an entity command which you can create a JPA Entity class quickly.
Type entity jpa in the Roo console and press TAB, you must specify a class name.
entity jpa --class ~.model.Conference --testAutomatically --activeRecord false
By default, Roo will apply the ActiveRecord pattern to generate the Entity class, the entity related classes will include all business logic(such as CRUD operations). In this demo, ~ is short for the base package name - com.hantsylabs.example.spring.conference which is set when the project was created before. --testAutomatically tell Roo to generate entity test codes automatically.
After you executed the command, you will find the path of Roo is switched to the created Conference class. You can add some fields into this Entity class.
field string --fieldName name --notNull 
field string --fieldName description 
field date --fieldName startedDate --type java.util.Date --notNull 
field date --fieldName endedDate --type java.util.Date --notNull 
field string --fieldName slug --notNull 
Now you have created a Conference entity class and it includes some fields.
For a multi layered application, you should create a Service layer and a Repository for your application. Roo aslo can help you to create a ConferenceRepository class and ConferenceService class for the Conference entity quickly, type in either of the following commands in Roo console.
repository jpa --entity ~.model.Conference --interface ~.repository.ConferenceRepository
service --entity ~.model.Conference --interface ~.service.ConferenceService
As motioned before, if you used activeRecord to generate the entity class, you do not need these steps, all database related operation are included in the entity related class.
Let us create another entity Signup to demonstrate this feature.
entity jpa --class ~.model.Signup --testAutomatically 
field string --fieldName firstName --notNull 
field string --fieldName lastName --notNull 
field string --fieldName email --notNull 
field string --fieldName phone --notNull 
field string --fieldName occupation  
field string --fieldName company  
field string --fieldName comment  
field date --type java.util.Date --fieldName createdAt --notNull 
Set the relation between Conference and Signup as ONE_TO_MANY.
field reference --fieldName conference --type ~.model.Conference --notNull 
field set --type ~.model.Signup --class ~.model.Conference --fieldName signups --cardinality ONE_TO_MANY 

Create the web layer

By default, Roo provides several options for the web layer solution, Spring MVC, GWT and JSF are supported.
For example, use the following commands to generate the web codes using Spring MVC.
web mvc setup
web mvc all --package  ~.web
There are several options provided in the web mvc command which can help you to create the controllers, pages etc.
I use web mvc all --package ~.web to generate the codes according to the existing entity classes in the default way instead of generating them one by one.

Run the project

Roo has added Maven tomcat and jetty plugin configuration in the pom.xml.
You can simply execute the following command in your terminal(quit Roo console firstly if you are in Roo console):
mvn jetty:run
to run the project in the embedded jetty server or
mvn tomcat:run
to run it in the embedded tomcat server.
Navigate to http://localhost:8080/.


Optionally, you can use perform package command and you will get a war package in the target folder. Copy it the deployment folder of your favorite application server and deploy it into the server manually.
If you would like use Eclipse IDE, you can import the project as an Existing Maven project from Import wizard directly. Or execute perform eclipse to generate eclipse configuration and import the project as a normal Eclipse project. We will cover this topic in the next post. Then you can run the project as a Eclipse web project in Eclipse managed application server.
You can execute perform tests to run the tests in the projects.
roo>perform tests

...
-------------------------------------------------------
 T E S T S
-------------------------------------------------------
roo>
Results :
roo>
Tests run: 18, Failures: 0, Errors: 0, Skipped: 0
roo>
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 17.639s
[INFO] Finished at: Mon May 20 16:10:08 CST 2013
[INFO] Final Memory: 12M/176M
[INFO] ------------------------------------------------------------------------
Now you have created a web project and run it on the application server successfully.
As you see, via Roo command, you can easily select a solution from one to another for a certain domain. Roo provides various options for the persistence provider, database, web frameworks etc, you can choose them freely.
Roo also provides some extra online addons which provide extra features, you can install them manually in Roo console.
I will demonstrate the cloudfoundry addon in further posts.
Optionally, you can use security addon to setup the basic Spring Security configuration for the app and email to setup email configuration.

评论

此博客中的热门博文

AngularJS CakePHP Sample codes

Introduction This sample is a Blog application which has the same features with the official CakePHP Blog tutorial, the difference is AngularJS was used as frontend solution, and CakePHP was only use for building backend RESR API. Technologies AngularJS   is a popular JS framework in these days, brought by Google. In this example application, AngularJS and Bootstrap are used to implement the frontend pages. CakePHP   is one of the most popular PHP frameworks in the world. CakePHP is used as the backend REST API producer. MySQL   is used as the database in this sample application. A PHP runtime environment is also required, I was using   WAMP   under Windows system. Post links I assume you have some experience of PHP and CakePHP before, and know well about Apache server. Else you could read the official PHP introduction( php.net ) and browse the official CakePHP Blog tutorial to have basic knowledge about CakePHP. In these posts, I tried to follow the steps describ

JPA 2.1: Attribute Converter

JPA 2.1: Attribute Converter If you are using Hibernate, and want a customized type is supported in your Entity class, you could have to write a custom Hibernate Type. JPA 2.1 brings a new feature named attribute converter, which can help you convert your custom class type to JPA supported type. Create an Entity Reuse the   Post   entity class as example. @Entity @Table(name="POSTS") public class Post implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="ID") private Long id; @Column(name="TITLE") private String title; @Column(name="BODY") private String body; @Temporal(javax.persistence.TemporalType.DATE) @Column(name="CREATED") private Date created; @Column(name="TAGS") private List<String> tags=new ArrayList<>(); } Create an attribute convert

Auditing with Hibernate Envers

Auditing with Hibernate Envers The approaches provided in JPA lifecyle hook and Spring Data auditing only track the creation and last modification info of an Entity, but all the modification history are not tracked. Hibernate Envers fills the blank table. Since Hibernate 3.5, Envers is part of Hibernate core project. Configuration Configure Hibernate Envers in your project is very simple, just need to add   hibernate-envers   as project dependency. <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-envers</artifactId> </dependency> Done. No need extra Event listeners configuration as the early version. Basic Usage Hibernate Envers provides a simple   @Audited   annotation, you can place it on an Entity class or property of an Entity. @Audited private String description; If   @Audited   annotation is placed on a property, this property can be tracked. @Entity @Audited public class Signup implements Serializa