Dependency Injection Basics
A key aspect of Grails services is the ability to take advantage of the
Spring Framework's dependency injection capability. Grails supports "dependency injection by convention". In other words, 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.
As an example, given a service called
BookService
, if you place a property called
bookService
within a controller as follows:
class BookController {
def bookService
…
}
In this case, the Spring container will automatically inject an instance of that service based on its configured scope. All dependency injection is done by name. You can also specify the type as follows:
class AuthorService {
BookService bookService
}
NOTE: Normally the property name is generated by lower casing the first letter of the type. For example, an instance of the BookService
class would map to a property named bookService
.To be consistent with standard JavaBean convetions, if the first 2 letters of the class name are upper case, the property name is the same as the class name. For example, an instance of the MYhelperService
class would map to a property named MYhelperService
.See section 8.8 of the JavaBean specification for more information on de-capitalization rules.
Dependency Injection and Services
You can inject services in other services with the same technique. Say you had an
AuthorService
that needed to use the
BookService
, declaring the
AuthorService
as follows would allow that:
class AuthorService {
def bookService
}
Dependency Injection and Domain Classes
You can even inject services into domain classes, which can aid in the development of rich domain models:
class Book {
…
def bookService
def buyBook() {
bookService.buyBook(this)
}
}