Eliminating Code Noise with Groovy

Eliminating Code Noise with Groovy

Introduction

Java is the most widely used programming language running on the JVM. However, there are many other JVM-based languages, such as Groovy, Scala, JRuby, Jython, Kotlin, and so on. Among these, Groovy and Scala have now been widely adopted in the Java community and are popular. This article describes how to use the Groovy programming language in a Spring Boot application.

Groovy: A Java-Based Programming Language

Groovy is a Java-based programming language that runs on the JVM. It supports dynamic input, closures, meta-programming, operator overloading, and multi-line strings, making it a convenient language for developers. Groovy also offers many features similar to scripting languages, such as string interpolation and elegant loop structures. Additionally, the semicolon is optional, which helps improve development efficiency.

Groovy String

We can use single or double quotes to create a string in Groovy. When using single quotes, a character string is regarded as a java.lang.String, whereas when using double quotes, it is seen as a groovy.lang.GString. This allows for variable value support in strings.

def name = "zhangsan"
def amount = 120
println('My name is $ {name}')
println("My name is $ {name}")
println("He paid \ $$ {amount}")
def age = 20
print("Her age is $ {age}")

POJO Properties

In Java, we generally acquire and create Bean by creating private property and getter, setter methods for these properties. Although we can use the IDE to generate setter and getter, it is still a little complicated, especially after the additions and deletions of properties. In Groovy, we can create a Bean directly by declaring a property, and then use the object.property syntax to access them without having to create setter and getters.

package com.groovydemo.groovy.entity

class Stu {
    Integer id
    String name
    Integer age
}

Loop Syntax

In addition to conventional and for while loops, Groovy also supports various cyclic structures. For example, we can use the operator (..) iteration, as follows:

1. conventional for usage:
for (i in 0..5) {
    print("$ {i}")
}

2. using upto() to determine the lower and upper limits:
0.upto(3) {
    print("$ it")
}

3. using the times() from zero iteration:
5.times {
    print("$ it")
}

4. using step() of the lower and upper limits to the value of the iteration step using:
0.step(10, 2) {
    print("$ it")
}

Using Groovy in Spring Boot

We can use the IDE or the online Spring Boot Application Builder to create an application and select the Groovy programming language. To Maven build tool, we can use the gmavenplus-plugin to compile Groovy code.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
         version="4.0.0">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com</groupId>
    <artifactId>groovy-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>groovy-demo</name>
    <description>demo project for Spring Boot</description>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy</artifactId>
            <version>2.4.15</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <!-- Groovy -->
            <plugin>
                <groupId>org.codehaus.gmavenplus</groupId>
                <artifactId>gmavenplus-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>addSources</goal>
                            <goal>addTestSources</goal>
                            <goal>generateStubs</goal>
                            <goal>compile</goal>
                            <goal>testGenerateStubs</goal>
                            <goal>testCompile</goal>
                            <goal>removeStubs</goal>
                            <goal>removeTestStubs</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

Stu

package com.groovydemo.groovy.entity

class Stu {
    Integer id
    String name
    Integer age
}

StuController

package com.groovydemo.groovy.controller

import com.groovydemo.groovy.entity.Stu
import com.groovydemo.groovy.service.StuService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

@RestController
@RequestMapping("Stu")
class StuController {
    @Autowired
    private StuService service

    @GetMapping("/test")
    String test() {
        Stu stu = service.getStuByid(1)
        return "Ok ==> You can use groovy!"
    }
}

StuService

package com.groovydemo.groovy.service

import com.groovydemo.groovy.entity.Stu

interface StuService {
    Stu getStuByid(int i)
}

StuServiceImpl

package com.groovydemo.groovy.service.impl

import com.groovydemo.groovy.entity.Stu
import com.groovydemo.groovy.service.StuService
import org.springframework.stereotype.Service

@Service
class StuServiceImpl implements StuService {
    @Override
    Stu getStuByid(int i) {
        Stu stu = new Stu()
        stu.setId(1)
        stu.setName("zhangsan")
        stu.setAge(18)
        return stu
    }
}

RunAppGroovy

package com.groovydemo

import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication

@SpringBootApplication
class RunAppGroovy {
    static void main(String[] args) {
        SpringApplication.run(RunAppGroovy.class, args)
    }
}

Access

HTTP: // localhost: 8080 / Stu / the Test

The results are as follows:

Ok ==> You can use groovy!

This article has been shared on Tencent Cloud’s media-sharing plan, and you are welcome to join and share together.