Spring Boot is a powerful framework for building Java-based, production-ready applications with minimal fuss. Whether you’re a seasoned Java developer or just starting your programming journey, Spring Boot offers a streamlined way to create robust, scalable, and maintainable applications.

In this Spring Boot Crash Course, I will take you on a step-by-step journey through the world of Spring Boot. By the end of this course, you will have a solid foundation in Spring Boot development and be ready to create your own Java applications with ease.

This first part of the series, is designed to provide you with the fundamental knowledge and tools you need to begin your Spring Boot development journey.

Part 2 Is Now Available Here

Pre-Requisites:

  1. Make sure you are familiar with the basics of Java like OOP.
  2. Some API basics will help, but you can learn them along the way :)

What is Spring?

Before getting started, we need to understand what is Spring, because Spring Boot is just an streamlined extension of the Spring Framework designed to simplify the process of building production-ready Spring applications.

Spring is an open-source Java application framework that is widely used in the software development industry. It is built on two fundamental principles: dependency injection and Inversion of Control (IoC).

Dependency Injection (DI):

Dependency injection is a design pattern in which the components or objects that a class relies on (its dependencies) are provided from the outside, rather than being created within the class itself.

Spring facilitates dependency injection by allowing developers to define the relationships between classes and their dependencies. These dependencies are then injected into the class at runtime, creating loosely coupled code.

In this diagram:

  • The “PaymentProcessor” class depends on the “PaymentMethod” interface, which defines the contract for different payment methods.
  • The “CreditCardPayment” and “PayPalPayment” classes implement the “PaymentMethod” interface, providing specific implementations for payment processing methods.
  • The Spring container is responsible for configuring and injecting the chosen payment method (either “CreditCardPayment” or “PayPalPayment”) into the “PaymentProcessor” class at runtime.

In the context of Spring, this can be achieved through XML configuration files or Java annotations.

Inversion of Control (IoC):

IoC is a software design principle that reverses the flow of control in a system. Instead of the application controlling the flow of a program, control is inverted or shifted to a framework or container, such as Spring.

In traditional programming, classes often control the creation and management of their dependencies. In contrast, Spring takes control of these responsibilities, which is why it’s referred to as IoC.

With IoC, Spring manages the creation, configuration, and injection of dependencies, allowing developers to focus on the application’s core logic and functionalities.

Taking the above example, Spring IoC container, is responsible for injecting the selected payment method into the “PaymentProcessor” at runtime.

A Little Bit of History

Before the emergence of Spring, the Java 2 Enterprise Edition (J2EE) was the dominant platform for enterprise development. However, J2EE had several issues, including the complexity of Enterprise Java Beans (EJB), extensive plumbing code requirements, lack of unit testing support, and heavyweight applications due to the need to configure all Java EE features and hard-code dependencies.

In 2002, Rod Johnson introduced the idea of a framework that would simplify enterprise development. Initially called Interface21, it later became an open-source framework.

In 2003, Spring was officially released and gained rapid popularity, providing a more efficient and user-friendly alternative to J2EE.

In 2014, The Spring Boot project was introduced in 2014 to simplify the process of creating stand-alone, production-ready Spring-based applications.

Fast forward to 2022, Spring 6.0 was released, representing a major revision of the core framework. It used Jakarta EE9 as a baseline and took advantage of new features in Java 17. Spring Boot 3.0 also came out, remaining compatible with Spring 6.0.

What are Beans?

Beans are fundamental components in the Spring framework that represent the objects managed by the Spring container. These objects are created, configured, and managed by Spring, and they serve as the building blocks of a Spring application.

Simply put beans are java objects created and maintained by the Spring Framework instead of you at runtime.

Why Spring Boot and What We Will Be Building?

Spring Boot allows you to quickly bootstrap and set up a Spring project. It provides project templates, embedded web servers, and pre-configured dependencies, enabling you to get started with coding immediately.

Spring Boot is an excellent choice for building microservices, including RESTful web services and full-fledged web applications. It simplifies the development of web applications by providing embedded web servers like Tomcat, Jetty, and Undertow.

Finally, Getting Started

Let’s start by creating a basic Hello-World API in Spring Boot.

Step 1: Set up your development environment

Before you begin, make sure you have Java and a Java IDE (e.g., Eclipse, IntelliJ IDEA, or Visual Studio Code) installed. You can even use a basic notepad to get started. You’ll also need Maven or Gradle for managing dependencies, but for this example, we’ll just use the Maven binary provided by Spring Boot itself during project creation. So no need to install anything.

Step 2: Create a new Spring Boot project

You can create a new Spring Boot project using the Spring Initializr web tool or your IDE. Here’s how to use the Spring Initializr:

  1. Visit the Spring Initializr website: https://start.spring.io/
  2. Select your project settings:
  • Project: Maven Project
  • Language: Java
  • Spring Boot: 3.1.5 (Choose the latest stable version)
  • Group: com.example (use any group ID)
  • Artifact: helloworld (use any name you want)
  • Packaging: Jar
  • Java: 17 or greater
  • Dependencies: Add Spring-Web as a dependency

3. Click the “Generate” button to download a ZIP file containing your project structure.

Step 3: Open the project in your IDE

Extract the downloaded ZIP file, and open the project in your chosen IDE. I’ll use VS Code.

Step 4: Create a “Hello, World!” Controller

Create a new Java class in the src/main/java/com/example/helloworld package, for example, HelloController.java, and add the following code:

package com.example.helloworld;

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

@RestController
public class HelloController {
@RequestMapping("/")
public String hello() {
return "Hello, World!";
}
}

Step 5: Build and run the application

Open a terminal, navigate to your project’s root directory, and run the following command:

./mvnw spring-boot:run

For Windows, use mvnw.cmd instead of ./mvnw.

Once the application is running, open a web browser or use a tool like cURL to access the application at http://localhost:8080/. You should see "Hello, World!" displayed on the page.

We just created an API simply just by adding two annotations @RestController and @GetMapping to our code. Spring Boot handled everything else for us. But to summarize, The @RestController tells spring that this class will hold the methods that will be run when a request is made to a path defined by @GetMapping

Don’t worry, we will be going through the Spring-Web dependency and what these annotations do in the next parts.

Before wrapping up this module, we will also look at 2 optional but very important dependencies offered by Spring Boot to make our lives easier— Spring Developer Tools and Spring Actuator.

Spring DevTools Dependency:

Usually when you make any change to the Java code, you will need to stop your Spring Boot server (ctrl+c) and then restart it to see the changes.

With DevTools, any changes you make to the code are automatically picked up by the server without the need to stop and restart the server. Spring Boot leverages two classloaders: one for classes that don’t change (like third-party libraries) and another for application code using the RestartClassLoader. When you make code changes, only the RestartClassLoader is reloaded, making the restart much faster.

To enable these features, you need to add the Spring Boot DevTools dependency to your project’s pom.xml file. You can do this by adding the following lines:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>

Now, when you run your server again, try changing the “Hello World” string in the return to something else like your name. The server should auto-reload when you hit save.

Spring Boot Actuator Dependency:

Spring Boot Actuator is a set of production-ready features that allows you to monitor and manage your Spring Boot application. It provides various built-in endpoints to retrieve information and statistics about your application’s runtime behavior.

To enable Spring Boot Actuator in your project, add the Actuator dependency in your pom.xml file just like before.

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Now, restart your server and try going to http://localhost:8080/actuator/health. You should see {“status”:”UP”} indicating that the Spring Boot server is running healthy.

Spring Boot Actuator exposes various endpoints that provide information and metrics about your application. But by default, only a few endpoints like /health and /info are available.

To expose all management endpoints via the web, you can add the following configuration in your application.properties or application.yml:

management.endpoints.web.exposure.include=*

This will make all Actuator endpoints accessible via HTTP.

Some commonly used Actuator endpoints include:

  • /auditevents: Shows audit information related to authentication and authorization.
  • /beans: Lists all Spring beans in the application.
  • /condition: Displays the conditions for autoconfiguration matches or mismatches.
  • /httptrace: Provides information about the last 100 HTTP requests.
  • /mappings: Shows all URI mappings (e.g., @RequestMapping endpoints).
  • /metrics: Lists valid metrics, and you can access specific metrics by adding their names to the URL.
  • /shutdown: Allows graceful shutdown of the application (when enabled).

This is great for development and testing but never do this in production as this would be a huge security risk.

A little hack for exploring Actuator:

To make it easier to explore the Actuator endpoints, you can add a HAL browser dependency in pom.xml.

<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-hal-browser</artifactId>
<version>3.3.6.RELEASE</version>
</dependency>

With the HAL browser enabled, you can explore Actuator endpoints through a web interface.

The HAL browser is accessible at http://localhost:8080/browser/index.html. You can type /actuator in the explorer, press "Go!", and it will show all exposed Actuator endpoints.

In the next parts, we will explore the Spring-Web dependency in depth and also explore how to properly work with databases in Spring Boot.

“Time is the only critic without ambition.” — John Steinbeck