Developing Your First Spring Boot Application

Learning Objectives

  • Set up a Spring Boot project using Spring Initializer
  • Understand basic project structure and dependencies
  • Create and understand the role of a REST controller
  • Implement and test a simple HTTP endpoint

Introduction

Java enterprise development has historically required complex configuration files and extensive boilerplate code. Spring Boot revolutionizes this approach by providing a streamlined, convention-over-configuration framework that has fundamentally changed how we build Java applications. In today's fast-paced development environment where rapid deployment cycles are essential, mastering Spring Boot has become indispensable for any Java developer.

The Spring Boot Journey

Spring Boot was born from the frustrations developers encountered with the traditional Spring Framework. While Spring provided robust dependency injection and enterprise-grade features, it demanded extensive XML configuration and significant setup time. Spring Boot eliminates these obstacles through intelligent defaults and seamless automatic configuration.

Imagine Spring Boot as a master chef who has already prepared all ingredients and arranged every tool before you begin cooking. You don't need to specify how to combine basic ingredients because those decisions follow established best practices. However, you maintain complete flexibility to customize any aspect when your specific requirements demand it.

Understanding the Magic

Spring Boot's core philosophy centers on its opinionated approach to application development. When you add a database dependency to your project, Spring Boot automatically configures the connection pool, transaction manager, and JPA settings without any manual intervention. This apparent "magic" stems from Spring Boot's auto-configuration system, which analyzes your classpath and configures components based on proven patterns and common use cases.

Creating Your First Spring Boot Project

We'll start by creating our project using Spring Initializer, which you can access at start.spring.io. This web-based tool represents the recommended approach for bootstrapping Spring Boot projects efficiently.

Navigate to https://start.spring.io and configure your project using these specifications:

Project settings:

Setting Value
Project Maven
Language Java
Spring Boot 3.4.0
Packaging Jar
Java Version 17

Project Metadata:

Setting Value
Group academy.javapro
Artifact demo
Name demo
Description First Spring Boot Application
Package name academy.javapro.demo

Dependencies:

Dependency Description Benefits
Spring Web REST API, Apache Tomcat Provides comprehensive web development capabilities including RESTful endpoints, MVC architecture support, and an embedded Apache Tomcat server. Essential for building modern web applications.
Spring Boot DevTools Development utilities Offers automatic application restarts when files change, live reload of browser resources, and enhanced development experience. Significantly improves developer productivity by reducing manual restart cycles.

Click "GENERATE" to download your project as a ZIP file. Extract the downloaded file to your preferred workspace directory.

Understanding the Project Structure

Spring Initializer has generated a complete, well-organized project structure:

javapro-hello-world/
├── src/
│   ├── main/
│   │   ├── java/
│   │   │   └── academy/
│   │   │       └── javapro/
│   │   │           └── HelloWorldApplication.java
│   │   └── resources/
│   │       ├── static/
│   │       ├── templates/
│   │       └── application.properties
│   └── test/
│       └── java/
├── .gitignore
├── mvnw
├── mvnw.cmd
└── pom.xml

The generated pom.xml file already contains all required dependencies:

<?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>3.4.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>academy.javapro</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>17</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-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </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>

Building Your First Endpoint

With our project structure established, let's create our controller package and implement our Hello World endpoint. Create a new package called controller under src/main/java/academy/javapro/:

package academy.javapro.demo.controller;

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

@RestController
public class HelloWorldController {

    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, JavaPro Academy!";
    }
}

The main application class was automatically generated:

package academy.javapro.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

Let's examine the key components of our application architecture:

  • @SpringBootApplication: This comprehensive annotation combines three essential annotations:

    • @Configuration: Designates the class as a source of bean definitions
    • @EnableAutoConfiguration: Activates Spring Boot's auto-configuration mechanism
    • @ComponentScan: Instructs Spring to scan for components in the current package and all sub-packages
  • @RestController: A convenient combination of two annotations:

    • @Controller: Identifies the class as a web controller
    • @ResponseBody: Indicates that method return values should be directly bound to the web response body
  • @GetMapping("/hello"): Maps HTTP GET requests to the specified URL path

Running and Testing

To execute your application:

  1. Run the DemoApplication class from your IDE
  2. Open your web browser and navigate to: http://localhost:8080/hello

You should see the message "Hello, JavaPro Academy!" displayed in your browser window.

Summary

Congratulations! You've successfully built your first Spring Boot application and gained valuable insights into Spring Boot fundamentals. Our simple Hello World application showcases several important Spring Boot features:

  • Auto-configuration: Spring Boot automatically configured an embedded Tomcat server, appropriate JSON message converters, and comprehensive error handling mechanisms without any manual configuration.
  • Dependency Management: The parent POM provides compatible dependency versions, proper plugin configurations, and Spring Boot-specific build features that eliminate version conflicts.
  • Development Tools: Spring Boot DevTools enables automatic application restart, built-in error handling, and enhanced debugging support that accelerates the development process.

In upcoming lessons, we'll explore building comprehensive RESTful APIs with multiple endpoints, handling various HTTP methods, working with request parameters and path variables, implementing robust error handling strategies, connecting to databases with JPA, and adding security layers to protect your applications.

Remember to practice creating additional endpoints, explore Spring Boot's extensive auto-configuration properties, and experiment with different annotations to deepen your understanding. The solid foundation you've established today will serve as the cornerstone for developing more sophisticated applications in your future projects.


Transform your future with Java Pro Academy's comprehensive Spring Boot course! Our Java Full Stack Developer program takes you from foundational concepts to advanced enterprise applications, guided by industry veterans who understand what employers need.

Transform your future with Java Pro Academy's comprehensive Spring Boot course! Our Java Full Stack Developer program takes you from foundational concepts to advanced enterprise applications, guided by industry veterans who understand what employers need. Master essential skills through hands-on projects that simulate real-world development scenarios, diving deep into data structures, algorithms, and Spring Boot architecture.

Whether you're starting your coding journey or advancing your existing skills, our intensive Java Bootcamp delivers practical expertise in modern full-stack development. Build a powerful portfolio while learning alongside passionate developers in our collaborative environment. Join Spring Boot Academy today and launch your career as a professional Java Full Stack Developer with confidence.

Complete Core Java Programming Course

Master Java from scratch to advanced! This comprehensive bootcamp covers everything from your first line of code to building complex applications, with expert guidance on collections, multithreading, exception handling, and more.

Leave a Comment