跳至主要内容

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.
发表评论

此博客中的热门博文

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 thePostentity 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 converter In this example…

Spring Data Mongo: bridge MongoDB and Spring

Spring Data Mongo: bridge MongoDB and SpringMongoDBis one of the most popular NoSQL products, Spring Data Mongo(Maven archetype id is spring-data-mongodb) tries to provides a simple approach to access MongoDB. Configuration Add the following code fragments in your Spring configuration. <!-- Mongo config --> <mongo:db-factory id="mongoDbFactory" host="localhost" port="27017" dbname="conference-db" /> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg ref="mongoDbFactory" /> </bean> <mongo:repositories base-package="com.hantsylabs.example.spring.mongo" /> Firstly, declare aDbFactorywhich is responsible for connecting to the MongoDB server. Then, register theMongoTemplateobject which envelop the data operations on MongoDB. Lastly addmongo:repositorieswith an essentialbase-packageattribute, Spring will discovery your d…

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 addhibernate-enversas 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@Auditedannotation, you can place it on an Entity class or property of an Entity. @Audited private String description; If@Auditedannotation is placed on a property, this property can be tracked.