Embedding the Groovy Grails Service in a Java Class

I have a Grails service implemented in Groovy that I would like to add to a Java class in a web application. I know that I can get a bean in Java through applicationContext.getBean ("exampleService"), but the ExampleService type is unknown at compile time.

Can I just import a service? It does not seem to be declaring a typical package.

(I am new to Grails and Java Web, so anything that helps me understand what is going on behind the scenes here is much appreciated.)

+4
source share
3 answers

The recommended approach is to extract the Grails service into the interface and then insert this service into your java class through Spring. See User Guide - http://www.grails.org/doc/1.3.x/guide/8.%20The%20Service%20Layer.html#8.4%20Using%20Services%20from%20Java

+7
source

If you want to introduce the Grails service in a Java class without using applicationContext.getBean("exampleService") , the Java class must be a Spring bean, and you must connect them together in both resources.groovy and resources.xml .

If the above does not make much sense to you, you may need to familiarize yourself with the basics of Spring dependency injection.

+2
source

According to what Donal said, you can associate a Java class with a bean in .groovy resources

For example, suppose 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') } } 

You should now have access to exampleService inside your java class, like a regular bean.

 def exampleService 

Although keep in mind that if you use something like intellij, a small bean icon may not appear next to it. This is normal. Also, be sure to import JavaClass into resources.groovy

0
source

Source: https://habr.com/ru/post/1382410/


All Articles