+ All Categories
Home > Documents > Grails 3.0 Framework - Spring Boot \"Gradle\"

Grails 3.0 Framework - Spring Boot \"Gradle\"

Date post: 12-Nov-2023
Category:
Upload: independent
View: 0 times
Download: 0 times
Share this document with a friend
14
JULY 2015 GRAILS 3.0 - WHAT’S NEW?
Transcript

JULY 2015

GRAILS 3.0 - WHAT’S NEW?

GRAILS 3.0 - WHAT’S NEW?

2

GRAILS 3.0 - WHAT’S NEW?

3

Introduction In a time when rapid web app development is the need of the hour and the sheer number of alternatives are enough to get any job done, one framework seems to have gained an edge among others. Started as ‘Groovy on Rails’ with a focus on eliminating the repetitive and cumbersome tasks of developing a traditional web application (back in 2005), Grails has come a long way.

What started out as a spring-hibernate-sitemesh wrapper has now turned into a RAD framework that supports various application profiles including standalone Groovy apps, modular support for NoSQL modules and out of the box REST API support. Grails has been nimble in moving with time. However, the last few months have seen what some might say are the biggest overhauls in the entire history of the Grails landscape. From Pivotal discontinuing funding to Grails finding a new home in OCI, the framework has seen many ups and downs.

The most noticeable change that affects the majority of the audience however is the rewrite of the Grails structure for 3.0, which is solely attributed to the introduction of Spring Boot as the backbone of the Grails framework. Gradle has been made the de facto build tool and even micro-web applications are now a native reality via Profiles.

This whitepaper illustrates our thoughts on this much hyped transition and the fallout for the general public.

GRAILS 3.0 - WHAT’S NEW?

2

GRAILS 3.0 - WHAT’S NEW?

3

1. Spring Boot Under The Hood

2. Gradle as de-facto Build tool

Spring Boot has made a developer’s life easier by letting them him create Spring-powered, production-ready applications and services without much effort. It eliminates boilerplate code and lengthy configuration steps which in turn decreases the ramp up time for a project. Grails has been completely re-written under the hood utilizing Spring Boot as its own delivery vehicle. Now by just building one app using Grails you are utilizing the power of 2 frameworks in one app.

The advantage being that while your Grails app is very lightweight, you get a plenty of options you would normally associate with Spring based apps - Actuator integration, Fat JAR’s, Starter POM’s, Spring 4.1 and what not !

Gradle is one aspect that is not new to Grails. There is already a Gradle plugin, for older Grails version (pre 3.0) though which now seems obsolete given that Gradle is the native build system for 3.0. The learning curve for using Gradle to create Grails 3.0 applications is negligible as the DSL used for adding dependencies, repositories is almost similar to BuildConfig.groovy which in turn has been removed completely from Grails 3.0. Given below is a sample of a build.gradle file where in you can instantly recognize the similarities with BuildConfig.groovy DSL.

repositories {

mavenLocal()

maven { url “https://repo.grails.org/grails/core” }

}

dependencies {

compile “org.springframework.boot:spring-boot-autoconfigure”

compile “org.springframework.boot:spring-boot-starter-tomcat”

console “org.grails:grails-console”

runtime “org.grails.plugins:scaffolding”

}

GRAILS 3.0 - WHAT’S NEW?

4

GRAILS 3.0 - WHAT’S NEW?

5

If you want to execute the gradle tasks directly instead of using the grails command line, use gradle wrapper. This way, you don’t need to download Grails executables and change the PATH variable to use “grails” command. Running “./gradlew bootRun” is same as running “grails run-app”. To know the tasks that are available to use with gradlew use “./gradlew -q tasks” command. Here is the sample output which lists all the available gradle tasks and a one liner description of those tasks:

3. Application Profiles

Profiles are a cool new feature of Grails (and is completely different concept compared to Spring Boot profiles) that allows you to move away from the traditional boundaries of web-apps and WAR files to building standalone runnable JARs and micro-web applications.

Whenever you use a ‘create-app’ command, Grails 3.0 uses a Profile to create the application skeleton. It encapsulates the project structure, commands, templates and plugins. The default profile is ‘web’ which represents the traditional web application deployable in a servlet container.

There are a couple of other profiles present like base, plugin, web-plugin and web-micro that allow you to package your application according to your needs. In the future more profiles are expected to be unveiled.

GRAILS 3.0 - WHAT’S NEW?

4

GRAILS 3.0 - WHAT’S NEW?

5

To create a project with a different Profile, simply use the --profile parameter:

grails create-app myapp --profile=web-micro BookApp

This will create only two files in BookApp project root: Application.groovy and application.yml. It is pretty lightweight. Here is the content of Application.groovy:

@Grab(“hibernate”)

@Grab(“h2”)

import grails.persistence.Entity

@Entity

@Resource(uri=”/books”)

class Book {

String name

}

Using @Grab annotation it adds hibernate and h2 database dependencies. Adding the beauty of the Grails @Resource annotation, you have a working application having various endpoints exposed through a single command.

HTTP Method URI Controller Action

GET /books Index

GET /books/create /create

POST /books Save

GET /books/${id} show

GET /books/$i{d}/edit edit

PUT /books/${id} update

DELETE /books/${id} delete

GRAILS 3.0 - WHAT’S NEW?

6

GRAILS 3.0 - WHAT’S NEW?

7

4. Plugins lifecycle events

is configurable in main application

as well

Now that‘s RAD for you. Read this for more insights into @Resource annotation.

The main class Application.groovy extends GrailsAutoConfiguration class which in turn implements GrailsApplicationLifeCycle interface and provides default implementation for the life cycle event methods such as doWithSpring, doWithDynamicMethods, doWithApplicationContext, onConfigChange, onStartup and onShutdown. These methods were available to Plugins only in earlier versions of Grails. The following sample Application.grooy overrides doWithDynamicMethods method to inject isAjax() method to all the controllers using meta-programming (the same could have been done using traits in better way):

class Application extends grails.boot.config.GrailsAutoConfiguration {

static void main(String[] args) { grails.boot.GrailsApp.run(this) }

@Override

public void doWithDynamicMethods() {

def grailsApplication = applicationContext getBean(‘grailsApplication’)

for (controllerClass in grailsApplication.controllerClasses) {

controllerClass.metaClass.isAjax = { ->

delegate.request.getHeader(“X-Requested-With”) == “XMLHttpRequest”

}

}

GRAILS 3.0 - WHAT’S NEW?

6

GRAILS 3.0 - WHAT’S NEW?

7

5. Traits: better way to add dynamic

behavior

For the doWithSpring event, you can do the same using grails-app/conf/spring/resources.groovy or grails-app/conf/spring/resources.xml by defining beans there. However there are some differences in the implicit objects accessible to both the approach.

The core API has been rewritten using groovy traits feature. The good thing with traits is that these are compatible with static compilation thus there is no runtime overhead when using it. This blog has some samples using different traits provided by Grails.

Let’s say we have some utility methods written which we want to inject in all the controllers and services at compile time. Define the trait as follows (your trait can implement predefined traits also as shown in the example below):

trait WebRequestHelper implements grails.web.api.WebAttributes {

Boolean isAjax() {

getWebRequest().getHeader(“X-Requested-With”) == “XMLHttpRequest”

}

Date today() {

return new Date().clearTime()

}

}

The next step is to tell Grails which artefacts you want to inject the trait into by adding a class that implements TraitInjector and overriding the respective methods as shown below:

GRAILS 3.0 - WHAT’S NEW?

8

GRAILS 3.0 - WHAT’S NEW?

9

6. Project StructureChanges

@groovy.transform.CompileStatic

class WebRequestUtilTraitInjector implements grails.compiler.traits.TraitInjector {

@Override

Class getTrait() {

return WebRequestHelper

}

@Override

String[] getArtefactTypes() {

[‘Controller’, ‘Service’] as String[]

}

}

And viola… you have injected all the methods from WebRequestHelper traits to all the controllers and services without and runtime overhead as they are done at compile time. You can use today() method inside any service/controller.

There are slight changes in the file structure due to a complete ground up rewrite of Grails. Some of the changes are due to the framework Spring Boot and some are due to the Gradle build tool. Locations for Java/Groovy sources are moved to src/main directory (maven style of source file structure) instead of placing them directly in src folder. Unit/Integration test class locations have also been changed and moved to src folder. Static assets can be placed in src/main/webapp folder. However the recommended way is to place the static assets in src/main/resources/public folder as they will be packaged even if you create JAR file instead of a WAR file. UrlMappings.groovy and BootStrap.groovy have been moved to new locations: grails-app/controller and grails-app/init respectively.

GRAILS 3.0 - WHAT’S NEW?

8

GRAILS 3.0 - WHAT’S NEW?

9

Some files have been removed completely e.g. BuildConfig.groovy, Datasource.groovy, application.properties etc. Few new files have been added e.g. build.gradle, Application.groovy, application.yaml, logback.groovy etc.The file structure changes is well explained here.

GRAILS 3.0 - WHAT’S NEW?

10

GRAILS 3.0 - WHAT’S NEW?

11

7. Application Configuration

Inspired by Spring Boot the default config file now is application.yml. YAML is a superset of JSON and is platform independent. Lot of frameworks have started using Yaml as their default format for specifying application configuration. However you might feel restricted as you can not use the power of Groovy DSL in Yaml file. The good news is that you can use application.groovy file to serve the same purpose as Config.groovy has been doing. Both application.yml and application.groovy can exist together and will be merged at runtime.

However there are some noticeable changes. Datasource.groovy file for specifying database settings is completely removed and settings is moved to application.yml/application.groovy.

The logging configuration has been moved to separate file: grails-app/conf/logback.groovy or grails-app/conf/logback.xml. Logback is the default logging framework used by Grails 3.0.

A good thing with application configuration in Grails 3.0 is that you can override them using OS environment variables and/or Java System properties. For the Heroku platform, we can see the benefit instantly, we don’t need to change the source code to make some configurations externalized, just define them as heroku config var and Heroku will restart your servers and your new configuration will override the default ones. This blog post describes Application Configurations in more details with some suggestions on using this in better way.

GRAILS 3.0 - WHAT’S NEW?

10

GRAILS 3.0 - WHAT’S NEW?

11

8. Spring way of request interception

Grails 2.x style filters are deprecated in Grails 3.x. It’s a good news for those who want to migrate their project from Grails 2.x, they can re-use the old filters for the time being. However it is recommended to not use the filters.

Grails 3.x has introduced a new artefact: Interceptor which implements Interceptor traits. You can leverage the power of CompileStatic annotation in interceptors for optimised performance as interceptor/filters are invoked for every request. Unlike Filter artefacts, Interceptors are placed in grails-app/controller folder. By default an interceptor will match only requests to the associated controller by convention e.g. DashboardInterceptor will be invoked for DashboardController. You can define non-trivial intercept rules using Interceptor Matcher. Here is an example interceptor that defines a non-trivial interceptor:

class DemoInterceptor {

DemoInterceptor() { // matcher defined in constructor

match(controller: “person”, action: “list”) // using strings

match(controller: ~/(department|store)/) // using regex

}

boolean before() {

println “From before method.”

true //returning false will cancel the execution of the action

}

boolean after() {

}

//you can modify model and view to use for the action

println “From after method. Model: “ + model + “, view: “ + view

GRAILS 3.0 - WHAT’S NEW?

12

GRAILS 3.0 - WHAT’S NEW?

13

true // returning false with cancel the view rendering

}

void afterView() { //no-op }

}

Upgradation of existing plugins

In addition to Spring-boot starter POM’s and lot of samples, we still miss the vast grails plugin repository. This blog points out some of the challenges and the community effort being made in migrating the plugins. The good news is that lot of plugins have been migrated and the Grails community is very active in migrating the remaining plugins. You can follow the steps here to migrate Grails 2.x applications including plugins to Grails 3.x. To just list a few migrated plugins: quartz, mail, console, asynchronous mail, cache, closure, geb, database-migration, mongodb, grails-redis etc.

You can change the order of execution of Interceptors if needed by defining an order property that defines a priority or by defining them in application config file like: beans.dashboardInteceptor.order= 50 //someIntegerValue

Note that if the interceptor does not match any controller by naming convention and if you have not defined proper matching rule, then it won’t work, you will get exceptions.

GRAILS 3.0 - WHAT’S NEW?

12

GRAILS 3.0 - WHAT’S NEW?

13

With Gradle as the new build tool and the rewrite of the framework using Spring Boot, a lot has changed internally. The in-place plugin concept is replaced by ordinary multi-project Gradle builds. The file structure changes have been tried to be as close as possible to Grails 2.x. Meta-magic has been avoided by using traits which adds behaviour at compile time thus reducing runtime overhead.

Grails has Adopted Spring Boot way of an Application class that has a standard main() method, and it can be used from your favourite IDE to execute or debug the application. There is no setup required for project specific grails version binaries/development kit in your IDE. The Grails 3 projects can be imported as a Gradle project in IDEs like IntelliJ Idea. Recent changes to Grails 3 have made it perform better than the Grails 2.x applications. You are no more limited to deploy the application using war file and setting up the Servlet container on production server. You can deploy the Grails 3.x applications in various ways including Fat jar, traditional war and self executable TAR/ZIP distribution.

You can keep yourself updated by watching the git repository. In addition to support on Google group and Stackoverflow, you can get in touch with the community on Slack as well.

Conclusion

With years of experience working in Groovy/Grails, Bhagwat is passionate about building software and mastering latest technologies. His knack for solving complex tasks and tackling difficult analytical problems has only been intensified at TO THE NEW.

Bhagwat is an accomplished team leader with a focus on results and timely delivery of products to customers with minimum technical glitches. He is considered a master craftsman by all his colleagues and has diverse experience in a wide range of technologies like Java, Grails, Spring Boot, NodeJS, AngularJS, Elasticsearch etc.

About the AuthorBhagwat Kumar

Technical Architect, TO THE NEW Digital

GRAILS 3.0 - WHAT’S NEW?

14

GRAILS 3.0 - WHAT’S NEW?

PB

Data Binding with GrailsGradle - Build System Evolved

[email protected]

www.tothenew.com

LET’S CONNECT

We are TO THE NEW Digital, a premium digital services company that uniquely combines the power of technology, analytics, creative and content for digital transformation.

Our passionate team of over 600 people includes technology evangelists, social media experts, content specialists, and creative mavericks who have transformed businesses of more than 300 companies spread across 30 countries worldwide.

About TO THE NEW Digital

Explore Other Resources

DOWNLOAD TUTORIAL DOWNLOAD TUTORIAL


Recommended