Provide Best Programming Tutorials

Use Java & Groovy together to build a Restful API.

This post will show you how to use Java & Groovy together to build a Restful API.

Make sure you have already installed the Groovy Library.

If not, you can go to this page to download it:https://groovy.apache.org/download.html

Tools we use:

  • IntelliJ IDEA
  • SpringBoot
  • Groovy

Steps:

  1. Create a SpringBoot project
  2. Add Groovy library support
  3. Write the code

Step 1 is easy so I will skip this part.

Step 2

Add the groovy library support.

Step 3

Write code using Groovy and Java

package com.andrewprogramming.groovyintegratewithspringboot.entity

class Course {
    String courseName;
    int courseId;

    Course(String courseName, int courseId) {
        this.courseName = courseName
        this.courseId = courseId
    }

    @Override
    String toString() {
        return "course name is:" + this.courseName + "," + "course id is:" + this.courseId;
    }
}
package com.andrewprogramming.groovyintegratewithspringboot.entity


class Person {
    int id;
    String name;
    Integer age;

    def courseList = [];

    Person(int id, String name) {
        this.id = id
        this.name = name
    }

    Person(int id, String name, Integer age) {
        this.id = id
        this.name = name
        this.age = age
    }

    Person(int id, String name, Integer age, courseList) {
        this.id = id
        this.name = name
        this.age = age
        this.courseList = courseList
    }

    def increaseAge(Integer years) {
        this.age += years;
    }

    def addCourse(Course course) {
        this.courseList.add(course)
    }
}

 

package com.andrewprogramming.groovyintegratewithspringboot.dao

import com.andrewprogramming.groovyintegratewithspringboot.entity.Person
import org.springframework.stereotype.Service

@Service
class PersonDao {
    def Person getPerson(int personId) {
        if (personId == 1) {
            return new Person(1, "person ID 1");
        }
        if (personId == 2) {
            return new Person(2, "person ID 2");
        }
    }
}

package com.andrewprogramming.groovyintegratewithspringboot.controller;

import com.andrewprogramming.groovyintegratewithspringboot.dao.PersonDao;
import com.andrewprogramming.groovyintegratewithspringboot.entity.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class PersonController {

    @Autowired
    private PersonDao personDao;

    @GetMapping("/person/{id}")
    public Person getPerson(@PathVariable String id) {
        return personDao.getPerson(1);
    }

}

Source Code

groovyintegratewithspringboot

 

Leave a Reply

Close Menu