跳至主要内容

Tao of Spring Roo

As you see, Spring Roo is not only a simple scollad tool for code generation, it also try to introduce a new programming model.

AspectJ and AOP programming

Roo is heavily dependent on AspectJ, the famous AOP framework, which is a subproject of Eclipse.org.
With the benifit of AspectJ, Roo try to separate the concern of an entity class.
The entity class itself focuses on the declaration of business fields, and only includes the basic definition of the properties and bean validation declaration, the JPA specific definitions are moved to _Roo_Jpa_Entity aspect, and the toString helper method is included in the _Roo_ToString aspect, the setter and getter methods of the properties are categorized in the _Roo_JavaBean aspect.
As you have seen in the before section, the entity class becomes slim and clean.
Roo will process the .aj files and compile them into classes at compile time. Thus all extra features in the .aj files will be accessible in the entity class at runtime.
In Eclipse IDE, open the Java editor, when you try to get code assistance of the method of class Signup, it will get completion options of all setters and getters of all properties and database CRUD operations. It is same to the later version of Signup class which have been remove all Roo specific features.
In pom.xml file, an aspectj maven plugin is declared, which will help to compile the .aj files into classes.



<plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>aspectj-maven-plugin</artifactId>
        <version>1.2</version>
        <!--NB: do not use 1.3 or 1.3.x due to MASPECTJ-90 and
        do not use 1.4 due to declare parents issue-->
        <dependencies>
            <!--NB: You must use
            Maven 2.0.9 or above or these are ignored (see MNG-2972)-->
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjrt</artifactId>
                <version>${aspectj.version}</version>
            </dependency>
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjtools</artifactId>
                <version>${aspectj.version}</version>
            </dependency>
        </dependencies>
        <executions>
            <execution>
                <goals>
                    <goal>compile</goal>
                    <goal>test-compile</goal>
                </goals>
            </execution>
        </executions>
        <configuration>
            <outxml>true</outxml>
            <aspectLibraries>
                <aspectLibrary>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-aspects</artifactId>
                </aspectLibrary>
            </aspectLibraries>
            <source>${java.version}</source>
            <target>${java.version}</target>
        </configuration>
</plugin>
 With the help of AJDT, you can switch between entity class and related the aspect quickly through the markers in the Java editor, you can also open the Cross Reference view to preview the pointcuts and advice.

ActiveRecord Pattern

Roo recommends you always use ActiveRecord pattern in your projects.
If you are a developer switched from Ruby on Rails, you will feel this pattern is very friendly.
But if you are Java web developer and familiar with the multi-layered architecture, you will feel a little incompatible. The codes are a little wired to you, especially after you have removed the the Roo specific features, the entity class becomes very fat.
Fortunately, Roo does not force you to choose AcitveRecord pattern in your project. You can freely select if use AcitveRecord pattern or not when you create an entity class. In order to disable ActiveRecord pattern, just need to specify a --activeRecord=false parameter to the entity command when creating an entity class. By default or set --activeRecord=true to the entity command, Roo will apply the AcitveRecord in the entity class.
ActiveRecord try to use single entity class to centralize all entity related operations. But it make the entity class become very heavy in a real world project. if you do not apply the ActiveRecord, you can choose the multi layered architecture, and create Repository and Service layer for your project respectively, the entity class will become very clean which only includes the mapping fields and some none transactional business logic.
In some books or articles, they are called Rich Model and Anemic Model respectively.
After you removed the Roo specific features, compare the Conference class(and ConferenceRepository and ConferenceService classes) and Signup class to get better understand of this pattern.
Multi Layered Architeture ActiveRecord
@Entity
public class Conference{
}

@Repository
public class ConferenceRepsoitory extends
    JpaRepository, 
    JpaSpecificationExecutor{


}

@Service
@Transactional
public class ConferenceService{
    @Autowired
    ConferenceRepository conferenceRepository;

}
@Configurable
@Transactional
@Entity
public class Signup{


    @Transactional
    public Signup save(){
    
    }

}

Record and Replay

Roo records every command you are using in the Roo console into log.roo file in project folder.
It looks like this.
// Spring Roo 1.2.3.RELEASE [rev 7fd62b6] log opened at 2012-12-29 11:49:48
project --topLevelPackage com.hantsylabs.example.spring
hint
jpa setup --provider HIBERNATE --database HYPERSONIC_IN_MEMORY 
hint
entity jpa --class ~.model.Conference --testAutomatically --activeRecord false
field string --fieldName name --notNull 
field string --fieldName description --notNull 
field date --fieldName startedDate --type java.util.Date --notNull 
field date --fieldName endedDate --type java.util.Date --notNull 
field string --fieldName slug --notNull 
hint
hint web mvc
web mvc setup
web mvc all --package  ~.web
selenium test --controller ~.web.ConferenceController
perform  tests
//.....
You can reload this file in Roo console to create a new Spring application quickly.
Enter Roo console, and execute script command.
roo> script --file log.roo
It will execute all commands in the log.roo.
More effectively, after you have familiarized with the commands provided by Roo, you can compose a script file firstly and then execute script command in the Roo console to load the script file to create your scaffold application quickly.

评论

此博客中的热门博文

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