Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using grails service in domain class

Tags:

grails

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?

like image 914
DonX Avatar asked Mar 17 '10 04:03

DonX


People also ask

What is grails 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.

What are grails services?

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.

How do I create a domain class in grails?

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.


1 Answers

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)) {
         ...
      }
   }
}
like image 102
Burt Beckwith Avatar answered Sep 20 '22 00:09

Burt Beckwith