SlideShare a Scribd company logo
Grails Services
Agenda
● Separation of concern
● Controller’s Responsibility
● Introduction of Service
● Create a Service
● Declaratives Transaction
● Transactions Rollback and Session
● Scoped Services
● Dependency Injection and Services
● Using Services from java
● Injecting a Service
hello!
I am Vijai Kumar Shukl
You can find me at vijay@nextho
1.
Separation of Concern
“Consider this analogy: Imagine a company where employees are assigned tasks on different nature of
work.
Consider Employee has following responsibility
● Handle accounting and releasing of check payments
● Take calls from customers for product support
● Handle administrative tasks such as booking flights plus accommodation of executives
● Manage the schedule of the CEO
Problem with this
1. Complicated to John
2. He have to change his frame of mind
3. It’s not easy to replace that employee
2.
Controller’s Responsibility
Consider a controller in Grails. Inside a controller, we can do the following:
● Handle routing logic
● Invoke GORM operations to manipulate data in the database
● Render text and show it to the user.
The real purpose of a controller is to deal with routing logic- which means
✘ Receive requests from users
✘ Invoke the most appropriate business logic
✘ Invoke the view to display the result
3.
Service Introduction
✘ All Business logic should be implemented in service layer.
✘ Grails has default support and handling for the service Layer.
✘ Services in Grails are the place to put the majority of the logic in your application, leaving
controllers responsible for handling request flow with redirects and so on.
4.
Creating A Service
grails create-service [package_name] [service_name]
A service's name ends with the convention Service,
other than that a service is a plain Groovy class
package com
class PublicService{
}
It will create two files:-
PublicService (Inside service folder)
PublicServiceSpec (Inside test folder)
grails create-service com Public
def publicService
5.
Declarative Transactions
Services are typically involved with coordinating logic between domain classes, and hence often involved with
persistence that spans large operations.
The nature of services, they frequently require transactional behaviour.
All services are transactional by default. To disable this set the transactional property to false
Note*:- Dependency is the only way that declarative transactions work. You will not get transactional behaviour if you
use new operator such as new PublicService()
The result is that all methods are wrapped in a transaction and automatic rollback occurs if a method throws a runtime
exception (i.e. one that extends RuntimeException) or an Error.
class PublicService{
static transactional = false
}
Custom Transaction Configuration
Grails also provides @Transactional and @NotTransactional annotations for cases:-
x Where you need more fine-grained control over transactions at a per-method level
x Need to specify an alternative propagation level.
x For example, the @NotTransactional annotation can be used to mark a particular method to be
skipped when a class is annotated with @Transactional.
class BookService{
@Transactional(readOnly=true)
def listBook(){
Book.list()
}
}
6.
Transactions Management
✘ Transaction is a very important concept. Hope you are well aware of ACID(Atomicity, Consistency,
Isolation, Durability) properties .
✘ Usually we wish certain sequence of database changes to be successful. If not possible we want no
operation to happen at all.
✘ Imagine a code that deducts money from one account (accountFrom.balance =
accountFrom.balance - amount), and adds money to another account (accountTo.balance =
accountTo.balance + amount). Imagine if something happened (an Exception) after deducting from
the source account and the destination account was not updated. Money will be lost and not
accounted for. For this type of codes, we want an "all or nothing" behavior. This concept is also called
atomicity.
✘ Since Grails supports transactions, it automatically do these things to us when we declare a service
to be transactional:
○ If all db operations are successful, reflect the changes to the database (this is also called commit) •
○ If one db operation result in exception, return to the original state and forget/undo all the previous operations
(this is also called rollback) •
✘ By default all services are transactional, if you don’t want transactional behavior of the service you
can get rid of it by class TestService(){ static transactional=false }
✘ When a transaction is rolled back the Hibernate Session used by GORM is cleared.
✘ Means an object within the session become detached and accessing uninitialized lazy-loaded
collections will lead to LazyInitiallizationExceptions.
7.
Scoped Services
By default, access to service methods is not synchronized, so nothing prevents concurrent execution of
those methods. In fact, because the service is a singleton and may be used concurrently, you should be
very careful about storing state in a service.
You can change this behaviour by placing a service in a particular scope. The supported scopes are:
● prototype - A new service is created every time it is injected into another class
● request - A new service will be created per request
● flash - A new service will be created for the current and next request only
● flow - In web flows the service will exist for the scope of the flow
● conversation - In web flows the service will exist for the scope of the conversation. ie a root flow
and its sub flows
● session - A service is created for the scope of a user session
● singleton (default) - Only one instance of the service ever exists
8.
Dependency Injection
A key aspect of Grails services is the ability to use Spring Framework's dependency injection features.
Grails supports "dependency injection by convention".
you can use the property name representation of the class name of a service to automatically inject them
into controllers, tag libraries, and so on.
class BookController{
def bookService
{
class BookController{
BookService bookService
{
class AuthorService{
def bookService
}
Our process is easy
create inject use
def appContext =
ServletContextHolder.servletContext.getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT)
def scrapeScoreService = appContext.scrapeScoreService
References
http://grails.asia/grails-tutorial-for-beginners-grails-service-layer/
http://docs.grails.org/2.4.4/guide/services.html
thanks!
Any questions?
You can find me at
vijay@nexthoughts.com

More Related Content

What's hot

Introduction to react js
Introduction to react jsIntroduction to react js
Introduction to react js
Aeshan Wijetunge
 
React.js
React.jsReact.js
A Brief Introduction to React.js
A Brief Introduction to React.jsA Brief Introduction to React.js
A Brief Introduction to React.js
Doug Neiner
 
React.js and Redux overview
React.js and Redux overviewReact.js and Redux overview
React.js and Redux overview
Alex Bachuk
 
Robust web apps with React.js
Robust web apps with React.jsRobust web apps with React.js
Robust web apps with React.js
Max Klymyshyn
 
React.js+Redux Workshops
React.js+Redux WorkshopsReact.js+Redux Workshops
React.js+Redux Workshops
Marcin Grzywaczewski
 
React-JS Component Life-cycle Methods
React-JS Component Life-cycle MethodsReact-JS Component Life-cycle Methods
React-JS Component Life-cycle Methods
ANKUSH CHAVAN
 
Understanding Facebook's React.js
Understanding Facebook's React.jsUnderstanding Facebook's React.js
Understanding Facebook's React.js
Federico Torre
 
Breaking the Server-Client Divide with Node.js and React
Breaking the Server-Client Divide with Node.js and ReactBreaking the Server-Client Divide with Node.js and React
Breaking the Server-Client Divide with Node.js and React
Dejan Glozic
 
Asynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesAsynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & Promises
Hùng Nguyễn Huy
 
Asynchronous Processing in Java/JEE/Spring
Asynchronous Processing in Java/JEE/SpringAsynchronous Processing in Java/JEE/Spring
Asynchronous Processing in Java/JEE/Spring
Naresh Chintalcheru
 
Redux workshop
Redux workshopRedux workshop
Redux workshop
Imran Sayed
 
Introduction to react
Introduction to reactIntroduction to react
Introduction to react
kiranabburi
 
Intro to React.js
Intro to React.jsIntro to React.js
Intro to React.js
Smita Prasad
 
React and redux
React and reduxReact and redux
React and redux
Mystic Coders, LLC
 
Introduction to React, Flux, and Isomorphic Apps
Introduction to React, Flux, and Isomorphic AppsIntroduction to React, Flux, and Isomorphic Apps
Introduction to React, Flux, and Isomorphic Apps
Federico Torre
 
Akka - Developing SEDA Based Applications
Akka - Developing SEDA Based ApplicationsAkka - Developing SEDA Based Applications
Akka - Developing SEDA Based Applications
Benjamin Darfler
 
Scaling React and Redux at IOOF
Scaling React and Redux at IOOFScaling React and Redux at IOOF
Scaling React and Redux at IOOF
Vivian Farrell
 

What's hot (20)

Introduction to react js
Introduction to react jsIntroduction to react js
Introduction to react js
 
React.js
React.jsReact.js
React.js
 
A Brief Introduction to React.js
A Brief Introduction to React.jsA Brief Introduction to React.js
A Brief Introduction to React.js
 
React.js and Redux overview
React.js and Redux overviewReact.js and Redux overview
React.js and Redux overview
 
Robust web apps with React.js
Robust web apps with React.jsRobust web apps with React.js
Robust web apps with React.js
 
React.js+Redux Workshops
React.js+Redux WorkshopsReact.js+Redux Workshops
React.js+Redux Workshops
 
React-JS Component Life-cycle Methods
React-JS Component Life-cycle MethodsReact-JS Component Life-cycle Methods
React-JS Component Life-cycle Methods
 
Understanding Facebook's React.js
Understanding Facebook's React.jsUnderstanding Facebook's React.js
Understanding Facebook's React.js
 
Breaking the Server-Client Divide with Node.js and React
Breaking the Server-Client Divide with Node.js and ReactBreaking the Server-Client Divide with Node.js and React
Breaking the Server-Client Divide with Node.js and React
 
Getting Started With ReactJS
Getting Started With ReactJSGetting Started With ReactJS
Getting Started With ReactJS
 
Asynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesAsynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & Promises
 
Asynchronous Processing in Java/JEE/Spring
Asynchronous Processing in Java/JEE/SpringAsynchronous Processing in Java/JEE/Spring
Asynchronous Processing in Java/JEE/Spring
 
Redux workshop
Redux workshopRedux workshop
Redux workshop
 
Introduction to react
Introduction to reactIntroduction to react
Introduction to react
 
Intro to React.js
Intro to React.jsIntro to React.js
Intro to React.js
 
React and redux
React and reduxReact and redux
React and redux
 
Callback Function
Callback FunctionCallback Function
Callback Function
 
Introduction to React, Flux, and Isomorphic Apps
Introduction to React, Flux, and Isomorphic AppsIntroduction to React, Flux, and Isomorphic Apps
Introduction to React, Flux, and Isomorphic Apps
 
Akka - Developing SEDA Based Applications
Akka - Developing SEDA Based ApplicationsAkka - Developing SEDA Based Applications
Akka - Developing SEDA Based Applications
 
Scaling React and Redux at IOOF
Scaling React and Redux at IOOFScaling React and Redux at IOOF
Scaling React and Redux at IOOF
 

Similar to Grails services

Grails Services
Grails ServicesGrails Services
Grails Services
NexThoughts Technologies
 
Autonomous transaction
Autonomous transactionAutonomous transaction
Autonomous transaction
Rajeev Rastogi (KRR)
 
Transaction design patterns
Transaction design patternsTransaction design patterns
Transaction design patterns
Ben Abdallah Helmi
 
Unit iv -Transactions
Unit iv -TransactionsUnit iv -Transactions
Unit iv -Transactions
Dhivyaa C.R
 
Ensuring Your Technology Will Scale
Ensuring Your Technology Will ScaleEnsuring Your Technology Will Scale
Ensuring Your Technology Will Scale
basissetventures
 
Microservices patterns
Microservices patternsMicroservices patterns
Microservices patterns
Vikram Babu Kuruguntla
 
Domain Logic Patterns
Domain Logic PatternsDomain Logic Patterns
Domain Logic Patterns
ElifTech
 
JS Fest 2019/Autumn. Anton Cherednikov. Choreographic or orchestral architect...
JS Fest 2019/Autumn. Anton Cherednikov. Choreographic or orchestral architect...JS Fest 2019/Autumn. Anton Cherednikov. Choreographic or orchestral architect...
JS Fest 2019/Autumn. Anton Cherednikov. Choreographic or orchestral architect...
JSFestUA
 
OutSystems community meetup 2018 11 service modules
OutSystems community meetup 2018 11 service modulesOutSystems community meetup 2018 11 service modules
OutSystems community meetup 2018 11 service modules
Kurt Vandevelde
 
Outsystems community meetup 2018 11 service modules
Outsystems community meetup 2018 11 service modulesOutsystems community meetup 2018 11 service modules
Outsystems community meetup 2018 11 service modules
Providit
 
Guidelines and Best Practices for Sencha Projects
Guidelines and Best Practices for Sencha ProjectsGuidelines and Best Practices for Sencha Projects
Guidelines and Best Practices for Sencha Projects
AmitaSuri
 
Building Cloud Ready Apps
Building Cloud Ready AppsBuilding Cloud Ready Apps
Building Cloud Ready Apps
VMware Tanzu
 
Distributed Transaction Management in Spring & JEE
Distributed Transaction Management in Spring & JEEDistributed Transaction Management in Spring & JEE
Distributed Transaction Management in Spring & JEE
Mushfekur Rahman
 
Rules Programming tutorial
Rules Programming tutorialRules Programming tutorial
Rules Programming tutorialSrinath Perera
 
Introduction to OSGi - Part-2
Introduction to OSGi - Part-2Introduction to OSGi - Part-2
Introduction to OSGi - Part-2
kshanth2101
 
Data power Performance Tuning
Data power Performance TuningData power Performance Tuning
Data power Performance TuningKINGSHUK MAJUMDER
 
Serverless Computing Model
Serverless Computing ModelServerless Computing Model
Serverless Computing Model
Mohamed Samir
 
TAG Presents: NetSuite SuiteFlow 101
TAG Presents: NetSuite SuiteFlow 101 TAG Presents: NetSuite SuiteFlow 101
TAG Presents: NetSuite SuiteFlow 101
TAG
 
'How to build efficient backend based on microservice architecture' by Anton ...
'How to build efficient backend based on microservice architecture' by Anton ...'How to build efficient backend based on microservice architecture' by Anton ...
'How to build efficient backend based on microservice architecture' by Anton ...
OdessaJS Conf
 
Jdk.io cloud native business automation
Jdk.io cloud native business automationJdk.io cloud native business automation
Jdk.io cloud native business automation
Ryan Dawson
 

Similar to Grails services (20)

Grails Services
Grails ServicesGrails Services
Grails Services
 
Autonomous transaction
Autonomous transactionAutonomous transaction
Autonomous transaction
 
Transaction design patterns
Transaction design patternsTransaction design patterns
Transaction design patterns
 
Unit iv -Transactions
Unit iv -TransactionsUnit iv -Transactions
Unit iv -Transactions
 
Ensuring Your Technology Will Scale
Ensuring Your Technology Will ScaleEnsuring Your Technology Will Scale
Ensuring Your Technology Will Scale
 
Microservices patterns
Microservices patternsMicroservices patterns
Microservices patterns
 
Domain Logic Patterns
Domain Logic PatternsDomain Logic Patterns
Domain Logic Patterns
 
JS Fest 2019/Autumn. Anton Cherednikov. Choreographic or orchestral architect...
JS Fest 2019/Autumn. Anton Cherednikov. Choreographic or orchestral architect...JS Fest 2019/Autumn. Anton Cherednikov. Choreographic or orchestral architect...
JS Fest 2019/Autumn. Anton Cherednikov. Choreographic or orchestral architect...
 
OutSystems community meetup 2018 11 service modules
OutSystems community meetup 2018 11 service modulesOutSystems community meetup 2018 11 service modules
OutSystems community meetup 2018 11 service modules
 
Outsystems community meetup 2018 11 service modules
Outsystems community meetup 2018 11 service modulesOutsystems community meetup 2018 11 service modules
Outsystems community meetup 2018 11 service modules
 
Guidelines and Best Practices for Sencha Projects
Guidelines and Best Practices for Sencha ProjectsGuidelines and Best Practices for Sencha Projects
Guidelines and Best Practices for Sencha Projects
 
Building Cloud Ready Apps
Building Cloud Ready AppsBuilding Cloud Ready Apps
Building Cloud Ready Apps
 
Distributed Transaction Management in Spring & JEE
Distributed Transaction Management in Spring & JEEDistributed Transaction Management in Spring & JEE
Distributed Transaction Management in Spring & JEE
 
Rules Programming tutorial
Rules Programming tutorialRules Programming tutorial
Rules Programming tutorial
 
Introduction to OSGi - Part-2
Introduction to OSGi - Part-2Introduction to OSGi - Part-2
Introduction to OSGi - Part-2
 
Data power Performance Tuning
Data power Performance TuningData power Performance Tuning
Data power Performance Tuning
 
Serverless Computing Model
Serverless Computing ModelServerless Computing Model
Serverless Computing Model
 
TAG Presents: NetSuite SuiteFlow 101
TAG Presents: NetSuite SuiteFlow 101 TAG Presents: NetSuite SuiteFlow 101
TAG Presents: NetSuite SuiteFlow 101
 
'How to build efficient backend based on microservice architecture' by Anton ...
'How to build efficient backend based on microservice architecture' by Anton ...'How to build efficient backend based on microservice architecture' by Anton ...
'How to build efficient backend based on microservice architecture' by Anton ...
 
Jdk.io cloud native business automation
Jdk.io cloud native business automationJdk.io cloud native business automation
Jdk.io cloud native business automation
 

More from Vijay Shukla

Introduction of webpack 4
Introduction of webpack 4Introduction of webpack 4
Introduction of webpack 4
Vijay Shukla
 
Preview of Groovy 3
Preview of Groovy 3Preview of Groovy 3
Preview of Groovy 3
Vijay Shukla
 
Jython
JythonJython
Jython
Vijay Shukla
 
Groovy closures
Groovy closuresGroovy closures
Groovy closures
Vijay Shukla
 
Groovy
GroovyGroovy
Groovy
Vijay Shukla
 
Grails plugin
Grails pluginGrails plugin
Grails plugin
Vijay Shukla
 
Grails domain
Grails domainGrails domain
Grails domain
Vijay Shukla
 
Grails custom tag lib
Grails custom tag libGrails custom tag lib
Grails custom tag lib
Vijay Shukla
 
Grails
GrailsGrails
Grails
Vijay Shukla
 
Gorm
GormGorm
Controller
ControllerController
Controller
Vijay Shukla
 
Config BuildConfig
Config BuildConfigConfig BuildConfig
Config BuildConfig
Vijay Shukla
 
Command object
Command objectCommand object
Command object
Vijay Shukla
 
Boot strap.groovy
Boot strap.groovyBoot strap.groovy
Boot strap.groovy
Vijay Shukla
 
Vertx
VertxVertx
Custom plugin
Custom pluginCustom plugin
Custom plugin
Vijay Shukla
 
Spring security
Spring securitySpring security
Spring security
Vijay Shukla
 
REST
RESTREST
Config/BuildConfig
Config/BuildConfigConfig/BuildConfig
Config/BuildConfig
Vijay Shukla
 
GORM
GORMGORM

More from Vijay Shukla (20)

Introduction of webpack 4
Introduction of webpack 4Introduction of webpack 4
Introduction of webpack 4
 
Preview of Groovy 3
Preview of Groovy 3Preview of Groovy 3
Preview of Groovy 3
 
Jython
JythonJython
Jython
 
Groovy closures
Groovy closuresGroovy closures
Groovy closures
 
Groovy
GroovyGroovy
Groovy
 
Grails plugin
Grails pluginGrails plugin
Grails plugin
 
Grails domain
Grails domainGrails domain
Grails domain
 
Grails custom tag lib
Grails custom tag libGrails custom tag lib
Grails custom tag lib
 
Grails
GrailsGrails
Grails
 
Gorm
GormGorm
Gorm
 
Controller
ControllerController
Controller
 
Config BuildConfig
Config BuildConfigConfig BuildConfig
Config BuildConfig
 
Command object
Command objectCommand object
Command object
 
Boot strap.groovy
Boot strap.groovyBoot strap.groovy
Boot strap.groovy
 
Vertx
VertxVertx
Vertx
 
Custom plugin
Custom pluginCustom plugin
Custom plugin
 
Spring security
Spring securitySpring security
Spring security
 
REST
RESTREST
REST
 
Config/BuildConfig
Config/BuildConfigConfig/BuildConfig
Config/BuildConfig
 
GORM
GORMGORM
GORM
 

Recently uploaded

GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
KrzysztofKkol1
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
ayushiqss
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Hivelance Technology
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
Jelle | Nordend
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
XfilesPro
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 

Recently uploaded (20)

GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 

Grails services

  • 2. Agenda ● Separation of concern ● Controller’s Responsibility ● Introduction of Service ● Create a Service ● Declaratives Transaction ● Transactions Rollback and Session ● Scoped Services ● Dependency Injection and Services ● Using Services from java ● Injecting a Service
  • 3. hello! I am Vijai Kumar Shukl You can find me at vijay@nextho
  • 5. “Consider this analogy: Imagine a company where employees are assigned tasks on different nature of work. Consider Employee has following responsibility ● Handle accounting and releasing of check payments ● Take calls from customers for product support ● Handle administrative tasks such as booking flights plus accommodation of executives ● Manage the schedule of the CEO Problem with this 1. Complicated to John 2. He have to change his frame of mind 3. It’s not easy to replace that employee
  • 7. Consider a controller in Grails. Inside a controller, we can do the following: ● Handle routing logic ● Invoke GORM operations to manipulate data in the database ● Render text and show it to the user. The real purpose of a controller is to deal with routing logic- which means ✘ Receive requests from users ✘ Invoke the most appropriate business logic ✘ Invoke the view to display the result
  • 9. ✘ All Business logic should be implemented in service layer. ✘ Grails has default support and handling for the service Layer. ✘ Services in Grails are the place to put the majority of the logic in your application, leaving controllers responsible for handling request flow with redirects and so on.
  • 11. grails create-service [package_name] [service_name] A service's name ends with the convention Service, other than that a service is a plain Groovy class package com class PublicService{ } It will create two files:- PublicService (Inside service folder) PublicServiceSpec (Inside test folder) grails create-service com Public def publicService
  • 13. Services are typically involved with coordinating logic between domain classes, and hence often involved with persistence that spans large operations. The nature of services, they frequently require transactional behaviour. All services are transactional by default. To disable this set the transactional property to false Note*:- Dependency is the only way that declarative transactions work. You will not get transactional behaviour if you use new operator such as new PublicService() The result is that all methods are wrapped in a transaction and automatic rollback occurs if a method throws a runtime exception (i.e. one that extends RuntimeException) or an Error. class PublicService{ static transactional = false }
  • 14. Custom Transaction Configuration Grails also provides @Transactional and @NotTransactional annotations for cases:- x Where you need more fine-grained control over transactions at a per-method level x Need to specify an alternative propagation level. x For example, the @NotTransactional annotation can be used to mark a particular method to be skipped when a class is annotated with @Transactional. class BookService{ @Transactional(readOnly=true) def listBook(){ Book.list() } }
  • 16. ✘ Transaction is a very important concept. Hope you are well aware of ACID(Atomicity, Consistency, Isolation, Durability) properties . ✘ Usually we wish certain sequence of database changes to be successful. If not possible we want no operation to happen at all. ✘ Imagine a code that deducts money from one account (accountFrom.balance = accountFrom.balance - amount), and adds money to another account (accountTo.balance = accountTo.balance + amount). Imagine if something happened (an Exception) after deducting from the source account and the destination account was not updated. Money will be lost and not accounted for. For this type of codes, we want an "all or nothing" behavior. This concept is also called atomicity. ✘ Since Grails supports transactions, it automatically do these things to us when we declare a service to be transactional: ○ If all db operations are successful, reflect the changes to the database (this is also called commit) • ○ If one db operation result in exception, return to the original state and forget/undo all the previous operations (this is also called rollback) • ✘ By default all services are transactional, if you don’t want transactional behavior of the service you can get rid of it by class TestService(){ static transactional=false }
  • 17. ✘ When a transaction is rolled back the Hibernate Session used by GORM is cleared. ✘ Means an object within the session become detached and accessing uninitialized lazy-loaded collections will lead to LazyInitiallizationExceptions.
  • 19. By default, access to service methods is not synchronized, so nothing prevents concurrent execution of those methods. In fact, because the service is a singleton and may be used concurrently, you should be very careful about storing state in a service. You can change this behaviour by placing a service in a particular scope. The supported scopes are: ● prototype - A new service is created every time it is injected into another class ● request - A new service will be created per request ● flash - A new service will be created for the current and next request only ● flow - In web flows the service will exist for the scope of the flow ● conversation - In web flows the service will exist for the scope of the conversation. ie a root flow and its sub flows ● session - A service is created for the scope of a user session ● singleton (default) - Only one instance of the service ever exists
  • 21. A key aspect of Grails services is the ability to use Spring Framework's dependency injection features. Grails supports "dependency injection by convention". you can use the property name representation of the class name of a service to automatically inject them into controllers, tag libraries, and so on. class BookController{ def bookService { class BookController{ BookService bookService { class AuthorService{ def bookService }
  • 22. Our process is easy create inject use
  • 25. thanks! Any questions? You can find me at vijay@nexthoughts.com