SlideShare a Scribd company logo
1 of 25
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

A Brief Introduction to React.js
A Brief Introduction to React.jsA Brief Introduction to React.js
A Brief Introduction to React.jsDoug Neiner
 
React.js and Redux overview
React.js and Redux overviewReact.js and Redux overview
React.js and Redux overviewAlex Bachuk
 
Robust web apps with React.js
Robust web apps with React.jsRobust web apps with React.js
Robust web apps with React.jsMax Klymyshyn
 
React-JS Component Life-cycle Methods
React-JS Component Life-cycle MethodsReact-JS Component Life-cycle Methods
React-JS Component Life-cycle MethodsANKUSH CHAVAN
 
Understanding Facebook's React.js
Understanding Facebook's React.jsUnderstanding Facebook's React.js
Understanding Facebook's React.jsFederico 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 ReactDejan Glozic
 
Asynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesAsynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesHù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/SpringNaresh Chintalcheru
 
Introduction to react
Introduction to reactIntroduction to react
Introduction to reactkiranabburi
 
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 AppsFederico Torre
 
Akka - Developing SEDA Based Applications
Akka - Developing SEDA Based ApplicationsAkka - Developing SEDA Based Applications
Akka - Developing SEDA Based ApplicationsBenjamin Darfler
 
Scaling React and Redux at IOOF
Scaling React and Redux at IOOFScaling React and Redux at IOOF
Scaling React and Redux at IOOFVivian 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

Unit iv -Transactions
Unit iv -TransactionsUnit iv -Transactions
Unit iv -TransactionsDhivyaa C.R
 
Ensuring Your Technology Will Scale
Ensuring Your Technology Will ScaleEnsuring Your Technology Will Scale
Ensuring Your Technology Will Scalebasissetventures
 
Domain Logic Patterns
Domain Logic PatternsDomain Logic Patterns
Domain Logic PatternsElifTech
 
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 modulesKurt 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 modulesProvidit
 
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 ProjectsAmitaSuri
 
Building Cloud Ready Apps
Building Cloud Ready AppsBuilding Cloud Ready Apps
Building Cloud Ready AppsVMware Tanzu
 
Distributed Transaction Management in Spring & JEE
Distributed Transaction Management in Spring & JEEDistributed Transaction Management in Spring & JEE
Distributed Transaction Management in Spring & JEEMushfekur 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-2kshanth2101
 
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 ModelMohamed 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 automationRyan 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 (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

Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 

Recently uploaded (20)

Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 

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