SlideShare ist ein Scribd-Unternehmen logo
1 von 8
SERVICES
WHY SERVICES
• Image a scenario of a company where employees are assigned tasks based on the nature
of their work. There is a employee Popeye who is the team leader so he has different
responsibilities such as :
• Handle client calls and guide them.
• Generate excel sheets with data for analysis.
• Manage schedule of team members .
• Schedule and look over calls for team members.
As you can see Popeye’s work is too hectic and complicated because all the tasks being
handled by them are of very different nature , he’s more likely to get stressed out and make
mistakes. His errors could cost a lot of money in the long run. Another problem is it's not easy
to replace Popeye as he is too involved in a complicated setup.
Likewise in software, it is not really a great idea to write a class with different responsibilities,
a single class or source file should only be involved in only one nature of task .If there is a lot
of things going on, this will only introduce bugs and problems later as the application will be
very complicated to maintain.
WHY NOT JUST CONTROLLER
Consider a controller in Grails .Inside a controller, we can do the following.
• Handle routing logic.
• Invoke GORM operations to manipulate data in database.
• Render text and show it to user.
However, it is not advisable that we do all those things inside a controller. Grails
allows a developers to do all these things together for flexibility, but it should be
avoided. The real purpose of a controller is to deal with the routing login which
means :
• Receive requests from user.
• Invoke the appropriate business login(services)
• Invoke the view to display result
DON’T REPEAT YOURSELF(DRY)
These days most of the technologies are following the DRY concept
which follows a strict practice of not having to duplicate code, using a
service layer is you could reuse a business logic in multiple places
without code duplication. Having a single copy of a particular business
logic will make a project shorter (in terms of lines of codes) and easier
to maintain. Changing the business logic will just require a change in
only one particular place.
CREATING A SERVICE
- To create a service , you can use create-service command from the root folder of your application.Ex.
grails create-service com.test.Test
The above command would create a TestService in com/test directory path .
- Or you can also create service from your ide.
- Service created would have the following content
package com.test
class TestService{
def serviceMethod(){
}
}
- You can go on adding as many method in the services having same nature of tasks.
INJECTING A SERVICE
• To use service methods , you would need to inject the service .
• Services can be injected in a controller , domain , tag libs,Bootstrap or another service.
• To inject a service in a controller
package com.test
class TestController{
def testService
def saveData(){
testService.serviceMethod()
}
}
TRANSACTION 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
}
SCOPE
• 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 You can change this behavior 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
• To enable one of the scopes, add a static scope property to your class whose value is one of the above. Ex
static scope=“session”

Weitere ähnliche Inhalte

Was ist angesagt?

Creating A User‑Defined Function In Excel Using Vba
Creating A User‑Defined Function In Excel Using VbaCreating A User‑Defined Function In Excel Using Vba
Creating A User‑Defined Function In Excel Using VbaChester Tugwell
 
How to create a REST pass through in Oracle Service Bus (OSB) 12c
How to create a REST pass through in Oracle Service Bus (OSB) 12cHow to create a REST pass through in Oracle Service Bus (OSB) 12c
How to create a REST pass through in Oracle Service Bus (OSB) 12ccoolaboration
 
Slideshare - Magento Imagine - Do You Queue
Slideshare - Magento Imagine - Do You QueueSlideshare - Magento Imagine - Do You Queue
Slideshare - Magento Imagine - Do You Queue10n Software, LLC
 
Graviton Approval Framework Presentation
Graviton Approval Framework PresentationGraviton Approval Framework Presentation
Graviton Approval Framework Presentationgravitonconsulting
 
Soap ui introduction
Soap ui introductionSoap ui introduction
Soap ui introductionIkuru Kanuma
 
Patterns of a "Good" Test Automation Framework, Locators & Data
Patterns of a "Good" Test Automation Framework, Locators & DataPatterns of a "Good" Test Automation Framework, Locators & Data
Patterns of a "Good" Test Automation Framework, Locators & DataAgile Testing Alliance
 
]project-open[ Workflow Developer Tutorial Part 1
]project-open[ Workflow Developer Tutorial Part 1]project-open[ Workflow Developer Tutorial Part 1
]project-open[ Workflow Developer Tutorial Part 1Klaus Hofeditz
 
Useful Salesforce.com chrome extensions & Snapshots
Useful Salesforce.com chrome extensions & SnapshotsUseful Salesforce.com chrome extensions & Snapshots
Useful Salesforce.com chrome extensions & SnapshotsProQuest
 
Test & Dynamics CRM - extremeCRM Berlin 2012
Test & Dynamics CRM - extremeCRM Berlin 2012Test & Dynamics CRM - extremeCRM Berlin 2012
Test & Dynamics CRM - extremeCRM Berlin 2012Wael Hamze
 
Webservices(or)SoapUI Interview Questions
Webservices(or)SoapUI Interview QuestionsWebservices(or)SoapUI Interview Questions
Webservices(or)SoapUI Interview QuestionsH2kInfosys
 
Web api 2 With MVC 5 With TrainerKrunal
Web api 2 With MVC 5 With TrainerKrunalWeb api 2 With MVC 5 With TrainerKrunal
Web api 2 With MVC 5 With TrainerKrunalKrunal Trivedi
 
Behavior-Driven Development and Automation Testing Using Cucumber Framework W...
Behavior-Driven Development and Automation Testing Using Cucumber Framework W...Behavior-Driven Development and Automation Testing Using Cucumber Framework W...
Behavior-Driven Development and Automation Testing Using Cucumber Framework W...KMS Technology
 
Testing Web Services - QA or the Highway 2016
Testing Web Services - QA or the Highway 2016Testing Web Services - QA or the Highway 2016
Testing Web Services - QA or the Highway 2016Steinn 'Stan' Jónsson
 

Was ist angesagt? (19)

Creating A User‑Defined Function In Excel Using Vba
Creating A User‑Defined Function In Excel Using VbaCreating A User‑Defined Function In Excel Using Vba
Creating A User‑Defined Function In Excel Using Vba
 
How to create a REST pass through in Oracle Service Bus (OSB) 12c
How to create a REST pass through in Oracle Service Bus (OSB) 12cHow to create a REST pass through in Oracle Service Bus (OSB) 12c
How to create a REST pass through in Oracle Service Bus (OSB) 12c
 
Slideshare - Magento Imagine - Do You Queue
Slideshare - Magento Imagine - Do You QueueSlideshare - Magento Imagine - Do You Queue
Slideshare - Magento Imagine - Do You Queue
 
Graviton Approval Framework Presentation
Graviton Approval Framework PresentationGraviton Approval Framework Presentation
Graviton Approval Framework Presentation
 
Soap ui introduction
Soap ui introductionSoap ui introduction
Soap ui introduction
 
Paper CS
Paper CSPaper CS
Paper CS
 
Patterns of a "Good" Test Automation Framework, Locators & Data
Patterns of a "Good" Test Automation Framework, Locators & DataPatterns of a "Good" Test Automation Framework, Locators & Data
Patterns of a "Good" Test Automation Framework, Locators & Data
 
MVC Training Part 2
MVC Training Part 2MVC Training Part 2
MVC Training Part 2
 
]project-open[ Workflow Developer Tutorial Part 1
]project-open[ Workflow Developer Tutorial Part 1]project-open[ Workflow Developer Tutorial Part 1
]project-open[ Workflow Developer Tutorial Part 1
 
Useful Salesforce.com chrome extensions & Snapshots
Useful Salesforce.com chrome extensions & SnapshotsUseful Salesforce.com chrome extensions & Snapshots
Useful Salesforce.com chrome extensions & Snapshots
 
Test & Dynamics CRM - extremeCRM Berlin 2012
Test & Dynamics CRM - extremeCRM Berlin 2012Test & Dynamics CRM - extremeCRM Berlin 2012
Test & Dynamics CRM - extremeCRM Berlin 2012
 
Functions creation in sql
Functions creation in sqlFunctions creation in sql
Functions creation in sql
 
Webservices(or)SoapUI Interview Questions
Webservices(or)SoapUI Interview QuestionsWebservices(or)SoapUI Interview Questions
Webservices(or)SoapUI Interview Questions
 
Learn SoapUI
Learn SoapUILearn SoapUI
Learn SoapUI
 
Angular vs FORWARD
Angular vs FORWARDAngular vs FORWARD
Angular vs FORWARD
 
Web api 2 With MVC 5 With TrainerKrunal
Web api 2 With MVC 5 With TrainerKrunalWeb api 2 With MVC 5 With TrainerKrunal
Web api 2 With MVC 5 With TrainerKrunal
 
Behavior-Driven Development and Automation Testing Using Cucumber Framework W...
Behavior-Driven Development and Automation Testing Using Cucumber Framework W...Behavior-Driven Development and Automation Testing Using Cucumber Framework W...
Behavior-Driven Development and Automation Testing Using Cucumber Framework W...
 
Datasense
DatasenseDatasense
Datasense
 
Testing Web Services - QA or the Highway 2016
Testing Web Services - QA or the Highway 2016Testing Web Services - QA or the Highway 2016
Testing Web Services - QA or the Highway 2016
 

Andere mochten auch (20)

Grails Plugins
Grails PluginsGrails Plugins
Grails Plugins
 
GORM
GORMGORM
GORM
 
Config BuildConfig
Config BuildConfigConfig BuildConfig
Config BuildConfig
 
Bootstrap
BootstrapBootstrap
Bootstrap
 
Unit testing
Unit testingUnit testing
Unit testing
 
Linux Introduction
Linux IntroductionLinux Introduction
Linux Introduction
 
Grails Views
Grails ViewsGrails Views
Grails Views
 
Introduction to Grails
Introduction to GrailsIntroduction to Grails
Introduction to Grails
 
Groovy
GroovyGroovy
Groovy
 
Groovy intro
Groovy introGroovy intro
Groovy intro
 
Meta Programming in Groovy
Meta Programming in GroovyMeta Programming in Groovy
Meta Programming in Groovy
 
Docker
DockerDocker
Docker
 
Introduction to mongo db
Introduction to mongo dbIntroduction to mongo db
Introduction to mongo db
 
Unit test-using-spock in Grails
Unit test-using-spock in GrailsUnit test-using-spock in Grails
Unit test-using-spock in Grails
 
Mixpanel
MixpanelMixpanel
Mixpanel
 
Actors model in gpars
Actors model in gparsActors model in gpars
Actors model in gpars
 
Grails Plugins(Console, DB Migration, Asset Pipeline and Remote pagination)
Grails Plugins(Console, DB Migration, Asset Pipeline and Remote pagination)Grails Plugins(Console, DB Migration, Asset Pipeline and Remote pagination)
Grails Plugins(Console, DB Migration, Asset Pipeline and Remote pagination)
 
Java reflection
Java reflectionJava reflection
Java reflection
 
MetaProgramming with Groovy
MetaProgramming with GroovyMetaProgramming with Groovy
MetaProgramming with Groovy
 
Grails Controllers
Grails ControllersGrails Controllers
Grails Controllers
 

Ähnlich wie Grails Services

Siebel best practices
Siebel best practicesSiebel best practices
Siebel best practicesSatish Vemula
 
SOA with Zend Framework
SOA with Zend FrameworkSOA with Zend Framework
SOA with Zend FrameworkMike Willbanks
 
Serverless Computing Model
Serverless Computing ModelServerless Computing Model
Serverless Computing ModelMohamed Samir
 
Patterns and practices for building enterprise-scale HTML5 apps
Patterns and practices for building enterprise-scale HTML5 appsPatterns and practices for building enterprise-scale HTML5 apps
Patterns and practices for building enterprise-scale HTML5 appsPhil Leggetter
 
Phil Green - We're migrating to the cloud - Who needs service management
Phil Green - We're migrating to the cloud - Who needs service managementPhil Green - We're migrating to the cloud - Who needs service management
Phil Green - We're migrating to the cloud - Who needs service managementitSMF UK
 
Чурюканов Вячеслав, “Code simple, but not simpler”
Чурюканов Вячеслав, “Code simple, but not simpler”Чурюканов Вячеслав, “Code simple, but not simpler”
Чурюканов Вячеслав, “Code simple, but not simpler”EPAM Systems
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2divzi1913
 
Microservices for java architects it-symposium-2015-09-15
Microservices for java architects it-symposium-2015-09-15Microservices for java architects it-symposium-2015-09-15
Microservices for java architects it-symposium-2015-09-15Derek Ashmore
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2Long Nguyen
 
Domain Logic Patterns
Domain Logic PatternsDomain Logic Patterns
Domain Logic PatternsElifTech
 
DevOps Introduction - Main Concepts Description
DevOps Introduction - Main Concepts DescriptionDevOps Introduction - Main Concepts Description
DevOps Introduction - Main Concepts DescriptionBrunoOliveira631137
 
Serverless Solutions for developers
Serverless Solutions for developersServerless Solutions for developers
Serverless Solutions for developersJuan Pablo
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing SoftwareSteven Smith
 
Cloud-based Test Microservices JavaOne 2014
Cloud-based Test Microservices JavaOne 2014Cloud-based Test Microservices JavaOne 2014
Cloud-based Test Microservices JavaOne 2014Shelley Lambert
 
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
 
Testing for Logic App Solutions | Integration Monday
Testing for Logic App Solutions | Integration MondayTesting for Logic App Solutions | Integration Monday
Testing for Logic App Solutions | Integration MondayBizTalk360
 
Reactive Micro Services with Java seminar
Reactive Micro Services with Java seminarReactive Micro Services with Java seminar
Reactive Micro Services with Java seminarGal Marder
 

Ähnlich wie Grails Services (20)

Grails services
Grails servicesGrails services
Grails services
 
Grails services
Grails servicesGrails services
Grails services
 
Siebel best practices
Siebel best practicesSiebel best practices
Siebel best practices
 
SOA with Zend Framework
SOA with Zend FrameworkSOA with Zend Framework
SOA with Zend Framework
 
Serverless Computing Model
Serverless Computing ModelServerless Computing Model
Serverless Computing Model
 
Patterns and practices for building enterprise-scale HTML5 apps
Patterns and practices for building enterprise-scale HTML5 appsPatterns and practices for building enterprise-scale HTML5 apps
Patterns and practices for building enterprise-scale HTML5 apps
 
Phil Green - We're migrating to the cloud - Who needs service management
Phil Green - We're migrating to the cloud - Who needs service managementPhil Green - We're migrating to the cloud - Who needs service management
Phil Green - We're migrating to the cloud - Who needs service management
 
Чурюканов Вячеслав, “Code simple, but not simpler”
Чурюканов Вячеслав, “Code simple, but not simpler”Чурюканов Вячеслав, “Code simple, but not simpler”
Чурюканов Вячеслав, “Code simple, but not simpler”
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2
 
Microservices for java architects it-symposium-2015-09-15
Microservices for java architects it-symposium-2015-09-15Microservices for java architects it-symposium-2015-09-15
Microservices for java architects it-symposium-2015-09-15
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2
 
Domain Logic Patterns
Domain Logic PatternsDomain Logic Patterns
Domain Logic Patterns
 
DevOps Introduction - Main Concepts Description
DevOps Introduction - Main Concepts DescriptionDevOps Introduction - Main Concepts Description
DevOps Introduction - Main Concepts Description
 
Serverless Solutions for developers
Serverless Solutions for developersServerless Solutions for developers
Serverless Solutions for developers
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
Cloud-based Test Microservices JavaOne 2014
Cloud-based Test Microservices JavaOne 2014Cloud-based Test Microservices JavaOne 2014
Cloud-based Test Microservices JavaOne 2014
 
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
 
Testing for Logic App Solutions | Integration Monday
Testing for Logic App Solutions | Integration MondayTesting for Logic App Solutions | Integration Monday
Testing for Logic App Solutions | Integration Monday
 
Reactive Micro Services with Java seminar
Reactive Micro Services with Java seminarReactive Micro Services with Java seminar
Reactive Micro Services with Java seminar
 

Mehr von 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
 

Kürzlich hochgeladen

How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 

Kürzlich hochgeladen (20)

How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 

Grails Services

  • 2. WHY SERVICES • Image a scenario of a company where employees are assigned tasks based on the nature of their work. There is a employee Popeye who is the team leader so he has different responsibilities such as : • Handle client calls and guide them. • Generate excel sheets with data for analysis. • Manage schedule of team members . • Schedule and look over calls for team members. As you can see Popeye’s work is too hectic and complicated because all the tasks being handled by them are of very different nature , he’s more likely to get stressed out and make mistakes. His errors could cost a lot of money in the long run. Another problem is it's not easy to replace Popeye as he is too involved in a complicated setup. Likewise in software, it is not really a great idea to write a class with different responsibilities, a single class or source file should only be involved in only one nature of task .If there is a lot of things going on, this will only introduce bugs and problems later as the application will be very complicated to maintain.
  • 3. WHY NOT JUST CONTROLLER Consider a controller in Grails .Inside a controller, we can do the following. • Handle routing logic. • Invoke GORM operations to manipulate data in database. • Render text and show it to user. However, it is not advisable that we do all those things inside a controller. Grails allows a developers to do all these things together for flexibility, but it should be avoided. The real purpose of a controller is to deal with the routing login which means : • Receive requests from user. • Invoke the appropriate business login(services) • Invoke the view to display result
  • 4. DON’T REPEAT YOURSELF(DRY) These days most of the technologies are following the DRY concept which follows a strict practice of not having to duplicate code, using a service layer is you could reuse a business logic in multiple places without code duplication. Having a single copy of a particular business logic will make a project shorter (in terms of lines of codes) and easier to maintain. Changing the business logic will just require a change in only one particular place.
  • 5. CREATING A SERVICE - To create a service , you can use create-service command from the root folder of your application.Ex. grails create-service com.test.Test The above command would create a TestService in com/test directory path . - Or you can also create service from your ide. - Service created would have the following content package com.test class TestService{ def serviceMethod(){ } } - You can go on adding as many method in the services having same nature of tasks.
  • 6. INJECTING A SERVICE • To use service methods , you would need to inject the service . • Services can be injected in a controller , domain , tag libs,Bootstrap or another service. • To inject a service in a controller package com.test class TestController{ def testService def saveData(){ testService.serviceMethod() } }
  • 7. TRANSACTION 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 }
  • 8. SCOPE • 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 You can change this behavior 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 • To enable one of the scopes, add a static scope property to your class whose value is one of the above. Ex static scope=“session”