BUILDING YOUR FIRST APPLICATION WITH SPRINGBOOT

B

This article would guide you on building your first Spring Boot Application. If you are new to Spring Boot and wondering how to build an application then you should continue reading.

What you will build

A simple web application that displays “hello world”. 

What you need

  • JDK 1.8 and above
  •  Maven
  • An IDE; using IntelliJ IDEA in this article 

Getting started

When starting a new Spring Boot project, there are two options:

  • Start a new project using your IDE. Go to File->New->Project. 
  • Using Spring Initialzr. This is my most preferred option because spring initialzr allows you to add all the configuration you need for the project, all you need is to download the generated zip file and start writing your code. In this project, I used Spring Initialzr.

Code Setup

A Sample Spring Initialzr Configuration

Using Spring Initialzr, Pick Java as your language and maven for the project. I used demo for my name and artifact because this is a sample project but you can use any name. For the dependency, I would be needing only the Spring Web dependency, its the dependency needed for building web, including RESTful applications using Spring MVC. 

Building the application

Once, you generate your project structure from spring initialzr, open the project using your IDE.

The project comes with a pom.xml file which contains your dependencies and configurations, it also comes with an Application class which is the main class for running your applications.

Web Controller

The next thing we would be doing is creating a controller class, a controller class in spring boot is responsible for processing incoming REST API request and returning the view to be rendered as a response.

package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

@GetMapping("/")

public String printGreeting(){
return "Hello World";
}

}

We used two annotations in the class:

  • @RestController to indicate that the class can handle web requests
  • @GetMapping to map “/” to the printGreeting method. It’s used for mapping HTTP Get requests onto specific handler methods.

RUnning the application

Now that we have all of the code we need, the next step is running the application.

To do that, you can either go to the terminal and run ./mvnw spring-boot:run or run the application from your IDE.

You should see something like this once your application is running:

testing the application

I used postman to test the application. By default, your application starts on port 8080 but I configured mine to start on 8082. 

To test, you can use this url:

http://localhost:8080/

 

SUmmary

You just successfully built a Spring Boot Web Application. You can also tweak the application to build what you want. Cheers! 

Add Comment

By admin

admin

Get in touch