SlideShare una empresa de Scribd logo
1 de 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

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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 a 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 a 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
 

Más de 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
 

Último

Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
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.
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
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.
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 

Último (20)

Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
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 ...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
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...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 

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