umma.dev

Spring Boot with Java

Spring Boot is a framework which enables users to build applications with languages such as Java and Kotlin. This post is an introduction to Spring Boot and how to set up, and run a Spring Boot application.

What is Spring Boot?

Spring Boot is a framework which enables users to build applications such as microservices.

Setting Up a Spring Boot Application

The first thing is to set up a new project with Spring Initializer. Head over to https://start.spring.io/, where you will see a list of options and change accordingly.

Spring allows you to search for dependencies such as web if you were building a REST API.

Select the dependencies required for the project and once the zip file has been downloaded, unzip it in the desired location.

Open up the project in IntelliJ or IDE of choice.

Building an End Point for REST API

In the source folder, create two folders and name them Controller and Model.

In Model create a new class, in this project it is called Person. In the person calss create private variables for a preson such as firstName and lastName. Create getters and setters for variables.

In the Controller create a class called PersonController, this is where the end point will be written.

package com.sbproject.firstProject.Controller;

import com.sbproject.firstProject.Model.Person;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class PersonController {
    @GetMapping("/person")
    public List<Person> getPerson()
    {
        List<Person> people = List.of(
                new Person("Person", "One", "1"),
                new Person("Person", "Two", "2")
        );
        return people;
    }

    @GetMapping("/person/{name}")
    public Person getPersons(@PathVariable String name)
    {
        List<Person> people = List.of(
                new Person("Person", "One", "1"),
                new Person("Person", "Two", "2"));

        Person person = people.stream()
                .filter(s -> s.getFirstName().equals(name))
                .findFirst()
                .orElseThrow(RuntimeException::new);

        return person;
    }
}

Every time a change is made the project has to be rebuilt, to do this type the following command line

./gradlew bootRun.

To create a build file or jar, use the following command line

./gradlew build

To run the jar file use the command line

Java .jar demo.jar