Home > Net >  How to run a Groovy script in my Spring Boot Application?
How to run a Groovy script in my Spring Boot Application?

Time:03-03

So I have an existing spring boot app. I want to add a Groovy script (let's say "HelloWorld.groovy") to display the message hello world. how can i do this? below is how i want it took like :

// some random code here
// ...
// ...
// groovy script : "HelloWorld" to be executed
// some random code ...

CodePudding user response:

There are a lot of different ways to do it and there isn't enough information in the question to know for sure what the best solution for you is going to be, but one way to do it is to create a GroovyShell and evaluate the script in that shell.

import groovy.lang.GroovyShell;

public class GroovyDemo {
    public static void main(String[] args) {
        System.out.println("This represents some random code");

        String groovyScript = "println 'first line of Groovy output'\n"  
                "println 'second line of Groovy output'";

        GroovyShell groovyShell = new GroovyShell();

        // instead of passing a String you could pass a
        // URI, a File, a Reader, etc... See GroovyShell javadocs
        groovyShell.evaluate(groovyScript);

        System.out.println("This represents some more random code");
    }
}

Output:

This represents some random code
first line of Groovy output
second line of Groovy output
This represents some more random code
  • Related