Spring Boot Basics: Crafting Your First Application
Tags: java, springboot, webdev, beginners
Published: 2023-06-24 18:57:46


![Spring Boot Logo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6x4evw3hatzwzqzanv53.png)
## 🚀 Introduction
Web application development stands at the core of building impactful solutions in almost every field and organization.
Among the many languages, [Java](https://dev.java/learn/) continues to stand tall and showcase its usefulness and longevity, having been ranked 3rd on the [Top Programming Languages at the 2022 Github Octoverse](https://octoverse.github.com/2022/top-programming-languages).
[Spring Boot](https://spring.io/projects/spring-boot), currently the most popular framework in the Java ecosystem, offers a simplified and versatile approach to building web applications. This article aims to provide a simplified roadmap for writing your first Spring Boot Java application.

### 📝 Prerequisites

Before starting with this tutorial, there are a few prerequisites you should take care of:

1. **Java Development Kit (JDK):** Spring Boot 2.4.0 and later requires at least Java 8. You can download the latest version of the JDK from Oracle's [official website](https://www.oracle.com/java/technologies/javase-jdk11-downloads.html).

2. **Integrated Development Environment (IDE):** A good IDE makes the development of Spring Boot applications simpler and easier. I recommend downloading and using [IntelliJ IDEA](https://www.jetbrains.com/idea/download/) but you are free to use any IDE of your choice like [Apache NetBeans](https://netbeans.apache.org/), [Eclipse](https://www.eclipse.org/downloads/packages/)or [VSCode](https://code.visualstudio.com/).

3. **Basic Java knowledge:** This tutorial assumes that you have a basic understanding of Java programming. You don't need to be an expert, but you should understand Java syntax and simple concepts like classes, objects, and methods. If you are new to Java,  feel free to check out this [Java For Beginners Series](https://learn.microsoft.com/en-us/shows/java-for-beginners/) by Microsoft, the [official Java learn website](https://dev.java/learn/) or any trusted source.

4. **Familiarity with Maven or Gradle:** Spring Boot uses these tools to manage dependencies. While it's not essential to have in-depth knowledge, a basic understanding of how these tools work will be useful. In this tutorial, we will use [Maven](https://maven.apache.org/guides/getting-started/maven-in-five-minutes.html).

### 🛠️ Create A New Spring Boot Application
**Spring Initializr** is a tool provided to help create Spring Boot applications easily.
1. Visit https://start.spring.io/. You should see something similar to the image below.
![Spring Intializr Image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vrggo4nv8zxllim8ee6s.png)
2. Select **Java** and **Maven** under the Project and Language sections respectively.
3. Select the Spring Boot version of your choice or leave it at the recommended version.
4. Name your project as you desire under the Project Metadata and choose a Java version as well.
3. In the **Dependencies** section, add `Spring Web` to create a web application.
4. Finally, click on the **Generate** button. This will download a .zip file containing your new Spring Boot project.

### 🧐 Exploring The Project Structure
Unzip the downloaded file and open the project in IntelliJ IDEA or your favourite IDE. Your project structure should look like this.

![Project Structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3knfxo2on7jwfab5gl4t.png)


#### 📂 Understanding The Project Structure

- `src`: This directory contains all the source code for the project.
    - `main`: This folder houses the primary source code for the application.
        - `java`: This is where all our Java source files reside.
            - `com/example/demo`: This is the package. .
                - `DemoApplication.java`: This is the main entry point for the Spring Boot application. Spring Boot applications bootstrap from a main method, which is contained in this class.
        - `resources`: This folder contains all non-code resources, like JSON, XML, properties files, and static web resources. It's also where we keep:
            - `application.properties`: This file is where you can specify application configurations, like server port, database connection info, etc.
    - `test`: This folder contains all of our test source code.
        - `java`: Here is where all our Java test files reside.
            - `com/example/demo`: This follows the same package structure as the main codebase.
                - `DemoApplicationTests.java`: This is where we write tests for our application.
- `.gitignore`: This file tells Git which files or directories to skip for version control.
- `pom.xml`: If you're using Maven as your build tool, this is where your project's dependencies and plugins are managed. In our case,  we are using Maven so our dependences will reside here.
- `README.md`: This file contains documentation of the project – what it does, how to set it up, and other useful information.

### ✍️ Writing Your First Controller
Controllers in Spring Boot handle incoming web requests and return responses. Let's create a simple controller. 
- Create a new file called `FirstController.java` in the same package as `DemoApplication.java`. You can name the controller anything you want.
Paste this code in your controller:

```java
package com.example.demo;

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

@RestController
public class FirstController {
    
    @GetMapping("/first")
    public String first() {
        return "My First Spring Boot App!";
    }
}

```

### 📖 Code Explanation
- `@RestController`: This is an annotation that is itself annotated with `@Controller` and `@ResponseBody`. `@Controller` is an annotation that marks the class as a web controller, capable of handling incoming `HTTP` requests. `@ResponseBody` indicates that the return values from the methods in this class will be bound to the HTTP response body.
- `@GetMapping("/first")`: This annotation is used to map `HTTP GET` requests onto specific handler methods. Here, it's mapping an `HTTP GET` request to the `/first` path to the **first()** method. When someone navigates to `/first` on your web service, the **first(){...}** method will be invoked.
- You can read more about Spring Annotations via the Spring official [reference documentation](https://docs.spring.io/spring-boot/docs/current/reference/html/) or access a cheat sheet [here](https://www.jrebel.com/blog/spring-annotations-cheat-sheet)

### 🏃 Running Your Application
- You can run your application easily from your IDE by clicking the `RUN` button of your IDE, normally shaped as a _Play button_.
You can also run the application from the terminal using the following command from the project root directory: `./mvnw spring-boot:run`

- Open your favorite browser and navigate to http://localhost:8080/first. You should see the message "My First Spring Boot App!".

![App Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q3ftra71hrx6ucdcc9l0.png)

**Note:** By default, Spring Boot applications run on port 8080. If you already have another application running on this port, you will encounter a port conflict, meaning your Spring Boot application won't start correctly. To resolve this, you can configure your Spring Boot application to use a different port. You can do this in the `application.properties` file like so:

```properties
server.port=9090
```
With this configuration, your application will run on port 9090 instead of the default port 8080.

## 🎉 Congratulations! 🎉

You've just developed your first Spring Boot Java application! This is merely the initial step in your journey with Spring Boot. The Spring Boot framework offers many other features 🚀 that you can delve into as you progress in your career as a developer.

Remember to practice consistently and always challenge yourself!
Happy coding! 🎊👩‍💻🎊

## 📚 References

1. [Official Spring Boot Documentation](https://spring.io/projects/spring-boot)
2. [Spring Boot Tutorials | Baeldung](https://www.baeldung.com/spring-boot)
3. [Building an Application with Spring Boot](https://spring.io/guides/gs/spring-boot/)