How to use existing java class from grails

How can I call a method that is in an existing Java class from a Grails application? Is it necessary / recommended to wrap this in a service?

+4
source share
5 answers

Put your source in src / java. Then in conf / spring / resources.groovy you can do, for example:

// Place your Spring DSL code here beans = { myJavaFunction(com.my.javafunction) } 

You can then enter it into your controllers or services with:

 def myJavaFunction 
+10
source

is the class in the jar file in your lib / folder or in the .java file of your src / folder?

In any case, there is no need to wrap it in a service. You can instantiate a class and call methods on it from anywhere.

If you need to wrap method calls in a transaction, I would put it in the service. Otherwise, just call directly. The only reason this is done in the service is to use the functionality (for example, if you need a new instance of the class created for each request).

amuses

Lee

+4
source

I thought I should post an update on how on Grails 2.2, since I looked around a lot and found a lot of non-local things that didn't seem to work, eventually made it work as follows:

 Project name: gp22 Grails Domain Example name: DemoGrailsDomain JavaClass:src/java/vv/Baggie.java Controller: DemoGrailsDomainController 

1: src / java / vv / Baggie.java

 package vv; import gp22.DemoGrailsDomain; public class Baggie { public int myresult(int value1) { int resultset=10+value1; return resultset; } public int getResult(int value1) { int aa=myresult(value1); return aa; //You can call your domain classes directly // Once called do a control shift o to pull in the above import example //DemoGrailsDomain getdomain = new DemoGrailsDomain(); } } 

DemoGrailsDomainController:

 def list(Integer max) { //def myJavaFunction Baggie a=new Baggie() int passit=5 def bb=a.getResult(passit); println "--"+bb 

Now make a change of control o on your controller and it will import vv.Baggie

Now, when I get to the list in the browser, println shows:

| The server is running. View on localhost: 8080 / gp22 --15 on my console

You have a value passed from the Grails controller to the processed and returned Java class, the Java class can also call Groovy Domains and retrieve information

+1
source

If you packed them into a .jar file, just drop the jar file into your / lib project

0
source

no need to wrap as a service. if you are using spring just add bean to resource.groovy

0
source

All Articles