I have a Grails-service implemented in Groovy, which I'd like to inject into a Java class, in the web application. I know I can get the bean in Java via applicationContext.getBean("exampleService"), but the type ExampleService is unknown at compile time.
Can I simply import the service? It doesn't seem to declare a typical package.
(I'm fairly new to Grails and the Java Web so anything to help my understanding of what's going on behind the scenes here is greatly appreciated.)
The recommended approach is to extract the Grails service into an interface, and then inject this service into your java class via Spring. See the user guide - http://www.grails.org/doc/1.3.x/guide/8.%20The%20Service%20Layer.html#8.4%20Using%20Services%20from%20Java
If you want to inject the Grails service into the Java class without using applicationContext.getBean("exampleService")
, the Java class must itself be a Spring bean, and you should wire the two together in either resources.groovy
or resources.xml
.
If the above doesn't make a lot of sense to you, you might want to read up on the basics of Spring dependency injection.
Following up with what Dónal said, you can wire the Java class as a bean in resources.groovy
For example, let's say the name of your java class is JavaClass, and it is located somewhere in your src folder. Go to resources.groovy and add the following to your beans...
beans = {
...
javaClass(JavaClass) {
exampleService = ref('exampleService')
}
}
Now you should be able to access exampleService inside your java class like a regular bean.
def exampleService
Though keep in mind that if you are using something like intellij the little bean icon might not appear next to it. This is normal. Also, don't forget to import JavaClass into resources.groovy