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

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

Rules Programming tutorial
Rules Programming tutorialRules Programming tutorial
Rules Programming tutorial
Srinath Perera
 
Data power Performance Tuning
Data power Performance TuningData power Performance Tuning
Data power Performance Tuning
KINGSHUK MAJUMDER
 

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

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

Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
mbmh111980
 

Recently uploaded (20)

AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAGAI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
 
SQL Injection Introduction and Prevention
SQL Injection Introduction and PreventionSQL Injection Introduction and Prevention
SQL Injection Introduction and Prevention
 
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdfImplementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdf
 
Lessons Learned from Building a Serverless Notifications System.pdf
Lessons Learned from Building a Serverless Notifications System.pdfLessons Learned from Building a Serverless Notifications System.pdf
Lessons Learned from Building a Serverless Notifications System.pdf
 
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdfMicrosoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
 
AI Hackathon.pptx
AI                        Hackathon.pptxAI                        Hackathon.pptx
AI Hackathon.pptx
 
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdfStrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
 
Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024
 
OpenChain @ LF Japan Executive Briefing - May 2024
OpenChain @ LF Japan Executive Briefing - May 2024OpenChain @ LF Japan Executive Briefing - May 2024
OpenChain @ LF Japan Executive Briefing - May 2024
 
Workforce Efficiency with Employee Time Tracking Software.pdf
Workforce Efficiency with Employee Time Tracking Software.pdfWorkforce Efficiency with Employee Time Tracking Software.pdf
Workforce Efficiency with Employee Time Tracking Software.pdf
 
OpenChain Webinar: AboutCode and Beyond - End-to-End SCA
OpenChain Webinar: AboutCode and Beyond - End-to-End SCAOpenChain Webinar: AboutCode and Beyond - End-to-End SCA
OpenChain Webinar: AboutCode and Beyond - End-to-End SCA
 
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
 
Crafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM IntegrationCrafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM Integration
 
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
 
AI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in MichelangeloAI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in Michelangelo
 
Optimizing Operations by Aligning Resources with Strategic Objectives Using O...
Optimizing Operations by Aligning Resources with Strategic Objectives Using O...Optimizing Operations by Aligning Resources with Strategic Objectives Using O...
Optimizing Operations by Aligning Resources with Strategic Objectives Using O...
 
How to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabberHow to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabber
 
A Guideline to Zendesk to Re:amaze Data Migration
A Guideline to Zendesk to Re:amaze Data MigrationA Guideline to Zendesk to Re:amaze Data Migration
A Guideline to Zendesk to Re:amaze Data Migration
 
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
 
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
 

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