Reputation: 1765
I'm pretty new to grails and spring
Me created a service
like this
services\com.mypackage\MyService
where
class MyService {
static transactional = true
def serviceMethod(params) {
println "params:"+params
}
}
Then when in my controller
controller\com.mypackage\mycontroller
Then in its action I tried to access like this
def myaction= {
com.mypackag.MyService myService //also used def myService
myService.serviceMethod(params)
render(view: "otherpage")
}
But it show the following error :(
java.lang.NullPointerException: Cannot invoke method serviceMethod() on null object
it cannot make the object of myservice.
myService shows null
What mistake i have done?
It will be very helpful if anyone provide me some good simple links and tutorials for using service with grails
Thank you
Upvotes: 1
Views: 1313
Reputation: 34823
One mistake you have done.
You are declaring that myService
inside your myaction
closures. Where it should be done in the controller
outside any of your methods or closures.
You can access your service methods using your service object (here myService) inside any of your methods or closures
So change like this
In your controller\com.mypackage\mycontroller
declare your service first
def myService
Then you can access it in any closures
def myaction= {
myService.serviceMethod(params)
render(view: "otherpage")
}
Upvotes: 4
Reputation: 187499
Your directory hierarchy does not correspond to you packages. You should change the directory hierarchy for your service to:
services\com\mypackage\MyService.groovy
and make sure you add the following at the top of MyService.groovy
package com.mypackage
class MyService {
// .....
}
Similarly, change the directory hierarchy for your controller to
controller\com\mypackage\MyController.groovy
Then to get a reference to your service inside your controller
// add the correct package statement
package com.mypackage
// rename the controller and the mycontroller.groovy file to MyController
class MyController {
// this will be injected by Spring (it must be named with a lower-case 'm')
def myService
def myaction= {
// use the service inside your action
myService.serviceMethod(params)
render(view: "otherpage")
}
}
Upvotes: 1
Reputation: 171084
1) I'd read the Grails User guide on Services
2) I'd make your services using the command line tools grails provides as it will save you putting things in invalid directories (com.mypackage
as a folder name is going to give you nothing but trouble), and it will make sure you have the correct package declarations at the top of your groovy files
Upvotes: 0