SlideShare a Scribd company logo
Grails Services
Agenda
● Separation of concern
● Controller’s Responsibility
● Introduction of Service
● Create a Service
● Declaratives Transaction
● Transactions Rollback and Session
● Scoped Services
● Dependency Injection and Services
● Using Services from java
● Injecting a Service
hello!
I am Vijai Kumar Shukl
You can find me at vijay@nextho
1.
Separation of Concern
“Consider this analogy: Imagine a company where employees are assigned tasks on different nature of
work.
Consider Employee has following responsibility
● Handle accounting and releasing of check payments
● Take calls from customers for product support
● Handle administrative tasks such as booking flights plus accommodation of executives
● Manage the schedule of the CEO
Problem with this
1. Complicated to John
2. He have to change his frame of mind
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
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

React.js+Redux Workshops
React.js+Redux WorkshopsReact.js+Redux Workshops
React.js+Redux Workshops
Marcin Grzywaczewski
 
Going towards inversion of control and better design
Going towards inversion of control and better designGoing towards inversion of control and better design
Going towards inversion of control and better designoazabir
 
Introduction to react
Introduction to reactIntroduction to react
Introduction to react
kiranabburi
 
React.js and Redux overview
React.js and Redux overviewReact.js and Redux overview
React.js and Redux overview
Alex Bachuk
 
[Java eeconf 2016] spring jta principles of work with transactions. Dmytro S...
[Java eeconf 2016] spring jta  principles of work with transactions. Dmytro S...[Java eeconf 2016] spring jta  principles of work with transactions. Dmytro S...
[Java eeconf 2016] spring jta principles of work with transactions. Dmytro S...
Dmytro Sokolov
 
Understanding Facebook's React.js
Understanding Facebook's React.jsUnderstanding Facebook's React.js
Understanding Facebook's React.js
Federico Torre
 
A Brief Introduction to React.js
A Brief Introduction to React.jsA Brief Introduction to React.js
A Brief Introduction to React.js
Doug Neiner
 
Redux workshop
Redux workshopRedux workshop
Redux workshop
Imran Sayed
 
reactJS
reactJSreactJS
reactJS
Syam Santhosh
 
Academy PRO: React JS. Redux & Tooling
Academy PRO: React JS. Redux & ToolingAcademy PRO: React JS. Redux & Tooling
Academy PRO: React JS. Redux & Tooling
Binary Studio
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation洪 鹏发
 
Introduction to React JS
Introduction to React JSIntroduction to React JS
Introduction to React JS
Arno Lordkronos
 
React js for beginners
React js for beginnersReact js for beginners
React js for beginners
Alessandro Valenti
 
React js
React jsReact js
React js
Rajesh Kolla
 
React and redux
React and reduxReact and redux
React and redux
Mystic Coders, LLC
 
Reactjs
Reactjs Reactjs
Reactjs
Neha Sharma
 
Introduction to React JS for beginners | Namespace IT
Introduction to React JS for beginners | Namespace ITIntroduction to React JS for beginners | Namespace IT
Introduction to React JS for beginners | Namespace IT
namespaceit
 
Better web apps with React and Redux
Better web apps with React and ReduxBetter web apps with React and Redux
Better web apps with React and Redux
Ali Sa'o
 

What's hot (20)

React.js+Redux Workshops
React.js+Redux WorkshopsReact.js+Redux Workshops
React.js+Redux Workshops
 
React JS - Introduction
React JS - IntroductionReact JS - Introduction
React JS - Introduction
 
Going towards inversion of control and better design
Going towards inversion of control and better designGoing towards inversion of control and better design
Going towards inversion of control and better design
 
Introduction to react
Introduction to reactIntroduction to react
Introduction to react
 
React.js and Redux overview
React.js and Redux overviewReact.js and Redux overview
React.js and Redux overview
 
[Java eeconf 2016] spring jta principles of work with transactions. Dmytro S...
[Java eeconf 2016] spring jta  principles of work with transactions. Dmytro S...[Java eeconf 2016] spring jta  principles of work with transactions. Dmytro S...
[Java eeconf 2016] spring jta principles of work with transactions. Dmytro S...
 
Understanding Facebook's React.js
Understanding Facebook's React.jsUnderstanding Facebook's React.js
Understanding Facebook's 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
 
Redux workshop
Redux workshopRedux workshop
Redux workshop
 
reactJS
reactJSreactJS
reactJS
 
Academy PRO: React JS. Redux & Tooling
Academy PRO: React JS. Redux & ToolingAcademy PRO: React JS. Redux & Tooling
Academy PRO: React JS. Redux & Tooling
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
 
Introduction to React JS
Introduction to React JSIntroduction to React JS
Introduction to React JS
 
React js for beginners
React js for beginnersReact js for beginners
React js for beginners
 
React js
React jsReact js
React js
 
React and redux
React and reduxReact and redux
React and redux
 
Getting Started With ReactJS
Getting Started With ReactJSGetting Started With ReactJS
Getting Started With ReactJS
 
Reactjs
Reactjs Reactjs
Reactjs
 
Introduction to React JS for beginners | Namespace IT
Introduction to React JS for beginners | Namespace ITIntroduction to React JS for beginners | Namespace IT
Introduction to React JS for beginners | Namespace IT
 
Better web apps with React and Redux
Better web apps with React and ReduxBetter web apps with React and Redux
Better web apps with React and Redux
 

Viewers also liked

G pars
G parsG pars
Grails internationalization-160524154831
Grails internationalization-160524154831Grails internationalization-160524154831
Grails internationalization-160524154831
NexThoughts Technologies
 
Grails custom tag lib
Grails custom tag libGrails custom tag lib
Grails custom tag lib
NexThoughts Technologies
 
Bootcamp linux commands
Bootcamp linux commandsBootcamp linux commands
Bootcamp linux commands
NexThoughts Technologies
 
Groovy intro
Groovy introGroovy intro
Meta Programming in Groovy
Meta Programming in GroovyMeta Programming in Groovy
Meta Programming in Groovy
NexThoughts Technologies
 
Groovy
GroovyGroovy
Docker
DockerDocker
Introduction to mongo db
Introduction to mongo dbIntroduction to mongo db
Introduction to mongo db
NexThoughts Technologies
 
Twilio
TwilioTwilio
Spring boot
Spring bootSpring boot
Gorm
GormGorm
Unit test-using-spock in Grails
Unit test-using-spock in GrailsUnit test-using-spock in Grails
Unit test-using-spock in Grails
NexThoughts Technologies
 
MetaProgramming with Groovy
MetaProgramming with GroovyMetaProgramming with Groovy
MetaProgramming with Groovy
NexThoughts Technologies
 
Java reflection
Java reflectionJava reflection
Java reflection
NexThoughts Technologies
 
Actors model in gpars
Actors model in gparsActors model in gpars
Actors model in gpars
NexThoughts Technologies
 
Grails Controllers
Grails ControllersGrails Controllers
Grails Controllers
NexThoughts Technologies
 
Groovy DSL
Groovy DSLGroovy DSL
Grails with swagger
Grails with swaggerGrails with swagger
Grails with swagger
NexThoughts Technologies
 
Command objects
Command objectsCommand objects
Command objects
NexThoughts Technologies
 

Viewers also liked (20)

G pars
G parsG pars
G pars
 
Grails internationalization-160524154831
Grails internationalization-160524154831Grails internationalization-160524154831
Grails internationalization-160524154831
 
Grails custom tag lib
Grails custom tag libGrails custom tag lib
Grails custom tag lib
 
Bootcamp linux commands
Bootcamp linux commandsBootcamp linux commands
Bootcamp linux commands
 
Groovy intro
Groovy introGroovy intro
Groovy intro
 
Meta Programming in Groovy
Meta Programming in GroovyMeta Programming in Groovy
Meta Programming in Groovy
 
Groovy
GroovyGroovy
Groovy
 
Docker
DockerDocker
Docker
 
Introduction to mongo db
Introduction to mongo dbIntroduction to mongo db
Introduction to mongo db
 
Twilio
TwilioTwilio
Twilio
 
Spring boot
Spring bootSpring boot
Spring boot
 
Gorm
GormGorm
Gorm
 
Unit test-using-spock in Grails
Unit test-using-spock in GrailsUnit test-using-spock in Grails
Unit test-using-spock in Grails
 
MetaProgramming with Groovy
MetaProgramming with GroovyMetaProgramming with Groovy
MetaProgramming with Groovy
 
Java reflection
Java reflectionJava reflection
Java reflection
 
Actors model in gpars
Actors model in gparsActors model in gpars
Actors model in gpars
 
Grails Controllers
Grails ControllersGrails Controllers
Grails Controllers
 
Groovy DSL
Groovy DSLGroovy DSL
Groovy DSL
 
Grails with swagger
Grails with swaggerGrails with swagger
Grails with swagger
 
Command objects
Command objectsCommand objects
Command objects
 

Similar to Grails services

Grails Services
Grails ServicesGrails Services
Grails Services
NexThoughts Technologies
 
Transaction design patterns
Transaction design patternsTransaction design patterns
Transaction design patterns
Ben Abdallah Helmi
 
Autonomous transaction
Autonomous transactionAutonomous transaction
Autonomous transaction
Rajeev Rastogi (KRR)
 
Building Cloud Ready Apps
Building Cloud Ready AppsBuilding Cloud Ready Apps
Building Cloud Ready Apps
VMware Tanzu
 
08 hopex v next service fabric
08 hopex v next   service fabric08 hopex v next   service fabric
08 hopex v next service fabric
Michel Bruchet
 
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
 
Serverless Computing Model
Serverless Computing ModelServerless Computing Model
Serverless Computing Model
Mohamed Samir
 
OutSystems community meetup 2018 11 service modules
OutSystems community meetup 2018 11 service modulesOutSystems community meetup 2018 11 service modules
OutSystems community meetup 2018 11 service modules
Kurt Vandevelde
 
Outsystems community meetup 2018 11 service modules
Outsystems community meetup 2018 11 service modulesOutsystems community meetup 2018 11 service modules
Outsystems community meetup 2018 11 service modules
Providit
 
Domain Logic Patterns
Domain Logic PatternsDomain Logic Patterns
Domain Logic Patterns
ElifTech
 
Unit iv -Transactions
Unit iv -TransactionsUnit iv -Transactions
Unit iv -Transactions
Dhivyaa C.R
 
Ensuring Your Technology Will Scale
Ensuring Your Technology Will ScaleEnsuring Your Technology Will Scale
Ensuring Your Technology Will Scale
basissetventures
 
Microservices patterns
Microservices patternsMicroservices patterns
Microservices patterns
Vikram Babu Kuruguntla
 
Guidelines and Best Practices for Sencha Projects
Guidelines and Best Practices for Sencha ProjectsGuidelines and Best Practices for Sencha Projects
Guidelines and Best Practices for Sencha Projects
AmitaSuri
 
'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
 
Siebel best practices
Siebel best practicesSiebel best practices
Siebel best practices
Satish Vemula
 
Externalized Distributed Configuration Management with Spring Cloud Config-Se...
Externalized Distributed Configuration Management with Spring Cloud Config-Se...Externalized Distributed Configuration Management with Spring Cloud Config-Se...
Externalized Distributed Configuration Management with Spring Cloud Config-Se...
Nikhil Hiremath
 
14843 lsampath wp_1 (1)
14843 lsampath wp_1 (1)14843 lsampath wp_1 (1)
14843 lsampath wp_1 (1)
jan_99in
 
Data power Performance Tuning
Data power Performance TuningData power Performance Tuning
Data power Performance TuningKINGSHUK MAJUMDER
 
Introduction to OSGi - Part-2
Introduction to OSGi - Part-2Introduction to OSGi - Part-2
Introduction to OSGi - Part-2
kshanth2101
 

Similar to Grails services (20)

Grails Services
Grails ServicesGrails Services
Grails Services
 
Transaction design patterns
Transaction design patternsTransaction design patterns
Transaction design patterns
 
Autonomous transaction
Autonomous transactionAutonomous transaction
Autonomous transaction
 
Building Cloud Ready Apps
Building Cloud Ready AppsBuilding Cloud Ready Apps
Building Cloud Ready Apps
 
08 hopex v next service fabric
08 hopex v next   service fabric08 hopex v next   service fabric
08 hopex v next service fabric
 
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...
 
Serverless Computing Model
Serverless Computing ModelServerless Computing Model
Serverless Computing Model
 
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
 
Domain Logic Patterns
Domain Logic PatternsDomain Logic Patterns
Domain Logic 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
 
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
 
'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 ...
 
Siebel best practices
Siebel best practicesSiebel best practices
Siebel best practices
 
Externalized Distributed Configuration Management with Spring Cloud Config-Se...
Externalized Distributed Configuration Management with Spring Cloud Config-Se...Externalized Distributed Configuration Management with Spring Cloud Config-Se...
Externalized Distributed Configuration Management with Spring Cloud Config-Se...
 
14843 lsampath wp_1 (1)
14843 lsampath wp_1 (1)14843 lsampath wp_1 (1)
14843 lsampath wp_1 (1)
 
Data power Performance Tuning
Data power Performance TuningData power Performance Tuning
Data power Performance Tuning
 
Introduction to OSGi - Part-2
Introduction to OSGi - Part-2Introduction to OSGi - Part-2
Introduction to OSGi - Part-2
 

More from NexThoughts Technologies

Alexa skill
Alexa skillAlexa skill
GraalVM
GraalVMGraalVM
Docker & kubernetes
Docker & kubernetesDocker & kubernetes
Docker & kubernetes
NexThoughts Technologies
 
Apache commons
Apache commonsApache commons
Apache commons
NexThoughts Technologies
 
HazelCast
HazelCastHazelCast
MySQL Pro
MySQL ProMySQL Pro
Microservice Architecture using Spring Boot with React & Redux
Microservice Architecture using Spring Boot with React & ReduxMicroservice Architecture using Spring Boot with React & Redux
Microservice Architecture using Spring Boot with React & Redux
NexThoughts Technologies
 
Swagger
SwaggerSwagger
Solid Principles
Solid PrinciplesSolid Principles
Solid Principles
NexThoughts Technologies
 
Arango DB
Arango DBArango DB
Jython
JythonJython
Introduction to TypeScript
Introduction to TypeScriptIntroduction to TypeScript
Introduction to TypeScript
NexThoughts Technologies
 
Smart Contract samples
Smart Contract samplesSmart Contract samples
Smart Contract samples
NexThoughts Technologies
 
My Doc of geth
My Doc of gethMy Doc of geth
My Doc of geth
NexThoughts Technologies
 
Geth important commands
Geth important commandsGeth important commands
Geth important commands
NexThoughts Technologies
 
Ethereum genesis
Ethereum genesisEthereum genesis
Ethereum genesis
NexThoughts Technologies
 
Ethereum
EthereumEthereum
Springboot Microservices
Springboot MicroservicesSpringboot Microservices
Springboot Microservices
NexThoughts Technologies
 
An Introduction to Redux
An Introduction to ReduxAn Introduction to Redux
An Introduction to Redux
NexThoughts Technologies
 
Google authentication
Google authenticationGoogle authentication
Google authentication
NexThoughts Technologies
 

More from NexThoughts Technologies (20)

Alexa skill
Alexa skillAlexa skill
Alexa skill
 
GraalVM
GraalVMGraalVM
GraalVM
 
Docker & kubernetes
Docker & kubernetesDocker & kubernetes
Docker & kubernetes
 
Apache commons
Apache commonsApache commons
Apache commons
 
HazelCast
HazelCastHazelCast
HazelCast
 
MySQL Pro
MySQL ProMySQL Pro
MySQL Pro
 
Microservice Architecture using Spring Boot with React & Redux
Microservice Architecture using Spring Boot with React & ReduxMicroservice Architecture using Spring Boot with React & Redux
Microservice Architecture using Spring Boot with React & Redux
 
Swagger
SwaggerSwagger
Swagger
 
Solid Principles
Solid PrinciplesSolid Principles
Solid Principles
 
Arango DB
Arango DBArango DB
Arango DB
 
Jython
JythonJython
Jython
 
Introduction to TypeScript
Introduction to TypeScriptIntroduction to TypeScript
Introduction to TypeScript
 
Smart Contract samples
Smart Contract samplesSmart Contract samples
Smart Contract samples
 
My Doc of geth
My Doc of gethMy Doc of geth
My Doc of geth
 
Geth important commands
Geth important commandsGeth important commands
Geth important commands
 
Ethereum genesis
Ethereum genesisEthereum genesis
Ethereum genesis
 
Ethereum
EthereumEthereum
Ethereum
 
Springboot Microservices
Springboot MicroservicesSpringboot Microservices
Springboot Microservices
 
An Introduction to Redux
An Introduction to ReduxAn Introduction to Redux
An Introduction to Redux
 
Google authentication
Google authenticationGoogle authentication
Google authentication
 

Recently uploaded

By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
Vlad Stirbu
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Enhancing Performance with Globus and the Science DMZ
Enhancing Performance with Globus and the Science DMZEnhancing Performance with Globus and the Science DMZ
Enhancing Performance with Globus and the Science DMZ
Globus
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 

Recently uploaded (20)

By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Enhancing Performance with Globus and the Science DMZ
Enhancing Performance with Globus and the Science DMZEnhancing Performance with Globus and the Science DMZ
Enhancing Performance with Globus and the Science DMZ
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 

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
  • 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
  • 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