跳至主要内容

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.

评论

此博客中的热门博文

Create a restful application with AngularJS and Zend 2 framework

Create a restful application with AngularJS and Zend 2 framework This example application uses AngularJS/Bootstrap as frontend and Zend2 Framework as REST API producer. The backend code This backend code reuses the database scheme and codes of the official Zend Tutorial, and REST API support is also from the Zend community. Getting Started with Zend Framework 2 Getting Started with REST and Zend Framework 2 Zend2 provides a   AbstractRestfulController   for RESR API producing. class AlbumController extends AbstractRestfulController { public function getList() { $results = $this->getAlbumTable()->fetchAll(); $data = array(); foreach ($results as $result) { $data[] = $result; } return new JsonModel(array( 'data' => $data) ); } public function get($id) { $album = $this->getAlbumTable()->getAlbum($id); return new JsonModel(array("data" =>

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