xain
xain

Reputation: 43

How to use existing java class from grails

how can I call a method residing in an existing Java class from Grails app ? Is it necessary/recommended to wrap that up in a service?

Upvotes: 4

Views: 7119

Answers (5)

V H
V H

Reputation: 8587

I thought I should send an update on the how to on grails 2.2, since I did a lot of looking around and found a lot of irrelevant stuff that did not appear to work, ended up making it work this way:

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

Do a control shift o on your contoller now, and it will import the vv.Baggie

Now when I hit the list on the browser the println shows:

| Server running. Browse to localhost:8080/gp22 --15 on my console

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

Upvotes: 1

Ford Guo
Ford Guo

Reputation: 971

there is no need to wrap as service. if you are using spring,just add the bean into resource.groovy

Upvotes: 0

Brad Rhoads
Brad Rhoads

Reputation: 1856

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)

}

Then you can inject it into your controllers or services with:

def myJavaFunction

Upvotes: 11

Luixv
Luixv

Reputation: 8710

If you have them packed in a .jar file then just drop the jar file into your-project/lib

Upvotes: 0

leebutts
leebutts

Reputation: 4882

is the class in a JAR file in your lib/ folder or in a .java file your src/ folder?

Either way, there's no need to wrap it in a service. You can construct instances of the class and call methods on it from anywhere.

If you need to wrap the method calls in a transaction then I'd put it in a service. Otherwise just call it directly. The only other reason to put it in a service is to use the scoping functionality (i.e. if you wanted a new instance of the class created for each request)

cheers

Lee

Upvotes: 4

Related Questions