Groovy and Grails: Changing the Landscape of Java™ Platform, Enterprise Edition (Java EE Platform) Patterns Graeme Rocher, CTO – G2One Inc Guillaume LaForge, VP of Engineering – G2One Inc TS-5793
Learn how Groovy through its powerful meta-programming techniques is enabling frameworks like Grails to change the way we think about patterns on the Java™ platform
Your Speakers
Graeme Rocher
Project Lead of Grails
CTO of G2One Inc – The Groovy/Grails Company
Member of JSR-241 (Java Specification Request) Expert Group
Author of “The Definitive Guide to Grails”
Your Speakers
Guillaume LaForge
Project Lead of Groovy
VP of Technology at G2One Inc – The Groovy/Grails Company
Lead of JSR-241 Expert Group
Co-Author of “Groovy in Action”
Agenda
Introduction and Why Groovy?
What makes a dynamic language?
Groovy’s Meta Object Protocol
Domain Specific Languages
Meta Programming Patterns
Applying Meta Programming techniques to Java EE platform patterns
The DAO
The Service Locator
What is Groovy?
Groovy is a dynamic language for the Java Virtual Machine (JVM)
Takes inspiration from Smalltalk, Python and Ruby
Integrates with the Java platform language and platform at every level
What is Grails?
A Web platform that implements the full stack from build system down to ORM layer
Leverages existing technologies like Spring, Hibernate, Quartz etc. avoiding re-inventing the wheel
Features and extensible plug-in system and an environment for runtime configuration built on Spring
Getting Started
Download from http://grails.org/Download
Extract zip to disk
Set GRAILS_HOME variable to location on disk
Add $GRAILS_HOME/bin to your environment variables
Download from http://groovy. codehaus .org
Extract zip to disk
Set GROOVY_HOME variable to location on disk
Add $GROOVY_HOME/bin to your environment variables
Why is Groovy dynamic?
A lot of confusion exists on what a factors make a language dynamic
Dynamic vs Static Typing
Strong vs. Weak Typing
Meta programming
Let’s clarify these!
Dynamic/Static/Weak/Strong
The Meta Object Protocol (MOP)
There are many dynamic languages
VB, Python, Ruby, Groovy, JavaScript™ technology
But, only a few have a MOP
Groovy
Ruby
LISP
Smalltalk
A MOP makes the semantics of a program extensible
Groovy’s MOP
Every class has a MetaClass, which can be obtained with:
The MetaClass defines the behaviour of the object and can be inspected:
def obj = "Hello World!" def metaClass = obj.metaClass obj. metaClass.methods .each { println it.name } Access the metaClass property The methods collection returns a list of MetaMethod instances
Using respondsTo and hasProperty
Need to find out whether an object implements a method? Use respondsTo :
Need to find out if an object has a property? Use hasProperty :
Instance methods can be added using the MetaClass:
As can properties using JavaBeans™ architecture conventions:
class Dog {} Dog. metaClass.bark = { "woof!" } println new Dog().bark() class Dog {} Dog. metaClass.getBreed = { "Bulldog" } println new Dog().breed Assigning a block of code to a property of the MetaClass creates a method! Properties need to follow JavaBeans naming coventions
Static Methods and Constructors
Static methods can be added using the static qualifier:
Constructors can be added using a special constructor property:
Dog.metaClass .static.bark = {new Dog() } println Dog.create().bark() Dog. metaClass .constructor = {String s -> new Dog(name:s) } println new Dog( "Fred" ).name Prefix the method name with the static qualifier to make a static method Careful of Stack overflows when overriding constructors!
Dog.metaClass . methodMissing = { String name, args-> println "Dogs don’t $name!" } def d = new Dog() d.quack() d.fly() "Dogs don’t quack!" "Dogs don’t fly!" No exception is thrown, the call is intercepted and the messages printed to system out Method missing allows you to intercept failed method dispatch
Meta-Programming Patterns
Intercept , Cache , Invoke
Enables code synthesis
Basic Usage:
Intercept method
Dynamically create new method
Cache new method
Invoke new method
First call takes performance hit, next call faster
Real Life Example: GORM in Grails class Album { String title String artist Date releaseDate static hasMany = [songs:Song] } class Song { String title Double duration } table - album table - song GORM classes, also known as domain classes, go in the domain directory id title artist release_date id title duration album_id
GORM in Action Querying and Persistence with GORM
Dynamic Finders & Criteria def albums = Album. list () def recentAlbums = Album. findAllByReleaseDateGreaterThan (new Date()-7) def albumsStartingWithA = Album. findAllByTitleLike ( "A%") def albumsWithSongsAboutSummer = Album. withCriteria { songs { like("title", "%Summmer%") } } List all records Form method expressions Use “like” queries Construct criteria on the fly to query associations
GORM Features
Dynamic finder and persistence methods
Criteria with a Groovy builder
Object-relational Mapping DSL
Caching
Legacy mapping
Locking strategy (optimistic/pessimistic)
Built on Hibernate
+
MOP == Goodbye to the DAO
Repetitive, boilerplate DAO logic gone (DRY)
Logic exists where it belongs - in the domain (DDD)
Automatic Dependency Injection Automatic Dependency Injection with Spring & Grails via Meta-programming
Real Life Example: Spring & Grails class Book { PurchasingService purchasingService Transaction buyBook(User u) { purchasingService.buyBook(this, u) } } Book. metaClass.constructor = {-> def obj = BeanUtils.instantiateClass(Book) applicationContext .getAutowireCapableBeanFactory() . autowireBeanProperties( obj, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false) return obj } Book domain class requires reference to PurchasingService Overriding default constructor for class Autowire dependencies into object from Spring at construction time
Real Life Example: Spring & Grails
Advantages of Meta way
Promotes Domain Driven Design (DDD)
No configuration
DRY
def user = User.get(1) def book = new Book() book.buyBook(user) All dependencies in place even when the new operator is used!
Summary
Meta-programming represents a new way to think about problems
Common patterns like the DAO and Service Locator are present because of limitations in Java platform
Groovy and Grails open doors to declarative programmings, DSLs and Domain Driven Design (DDD)
For More Information
Grails
TS-6457 - Choosing Your Java Technology-Based Web Framework: A Comparison
0 comments
Post a comment