12.4 Using Services from Java - Reference Documentation
Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith, Lari Hotari
Version: 3.0.11
12.4 Using Services from Java
One of the powerful things about services is that since they encapsulate re-usable logic, you can use them from other classes, including Java classes. There are a couple of ways you can reuse a service from Java. The simplest way is to move your service into a package within thegrails-app/services
directory. The reason this is important is that it is not possible to import classes into Java from the default package (the package used when no package declaration is present). So for example the BookService
below cannot be used from Java as it stands:class BookService { void buyBook(Book book) { // logic } }
grails-app/services/bookstore
and then modifying the package declaration:package bookstoreclass BookService {
void buyBook(Book book) {
// logic
}
}
package bookstoreinterface BookStore { void buyBook(Book book) }
class BookService implements bookstore.BookStore {
void buyBook(Book b) {
// logic
}
}
src/java
directory and add a setter that uses the type and the name of the bean in Spring:// src/java/bookstore/BookConsumer.java package bookstore;public class BookConsumer { private BookStore store; public void setBookStore(BookStore storeInstance) { this.store = storeInstance; } … }
grails-app/conf/spring/resources.xml
(for more information see the section on Grails and Spring):<bean id="bookConsumer" class="bookstore.BookConsumer"> <property name="bookStore" ref="bookService" /> </bean>
grails-app/conf/spring/resources.groovy
:import bookstore.BookConsumerbeans = { bookConsumer(BookConsumer) { bookStore = ref("bookService") } }