How to create Spring Boot Application 2021

Hi Devs,

Today I am going to show you how to create a simple spring boot project from scratch.

Go to spring initializer to generate a spring boot project.

Spring Initilizer

The pom.xml file looks like:

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.5.4</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>
   <groupId>com.codesnipeet</groupId>
   <artifactId>simple-project</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>simple-project</name>
   <description>simple project for Spring Boot</description>
   <properties>
      <java.version>11</java.version>
   </properties>
   <dependencies>
      <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>
      </plugins>
   </build>

</project>

Application.properties file

Go to the application.properties file and set the server port, by default the port is 8080. You can change it in the properties file.

server.port=9090

Create a controller

GO the the main folder and create a package name it controller, its the nameing conveniton to create the controllers in the controller package.

My controller name is HelloWorldController.java

package com.codesnipeet.controller;

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

@RestController
public class HelloWorldController {
    
    @GetMapping("/hello-world")
    public String displayMessage(){
        return "Hello spring boot World!";
    }
}

Run the project

Go to browser and enter the end-point and see the magic:

localhost:9090/hello-world

Output

Hope It helps: