I want to use a service in my Grails application. However, it is always null. I am using Grails version 1.1. How can I solve this problem?
Sample code:
class A{
String name;
def testService;
static transients=['testService']
}
Can I use a service inside a domain class?
In Grails a domain is a class that lives in the grails-app/domain directory. A domain class can be created with the create-domain-class command: grails create-domain-class org.bookstore.Book. or with your favourite IDE or text editor.
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.
If you don't specify a package (like "org. bookstore" in the example), then the name of the application will be used as the package. So if the application name is "bookstore" and you run create-domain-class Book , then the command will create the file grails-app/domain/bookstore/Book.
That should work. Note that since you're using 'def' you don't need to add it to the transients list. Are you trying to access it from a static method? It's an instance field, so you can only access it from instances.
The typical use case for injecting a service into a domain class is for validation. A custom validator gets passed the domain class instance being validated, so you can access the service from that:
static constraints = {
name validator: { value, obj ->
if (obj.testService.someMethod(value)) {
...
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With