Lesson 2
Understanding Spring Boot Project Structure
Introduction

Welcome back! In the previous lesson, you were introduced to Spring Boot and saw how it simplifies application development. Now, let's dive into understanding the project structure of a Spring Boot application. Grasping the project structure is crucial as it helps you know where to place your code and configuration files. By the end of this lesson, you'll have a clear understanding of the typical Spring Boot project layout and the purpose of specific files. You'll also cover some basic Gradle commands to help you manage your Spring Boot application efficiently.

Project Structure At a Glance

A typical Spring Boot project follows a standardized structure, especially when using Gradle as the build tool. Adhering to this structure ensures compatibility and ease of integration. Here's an outline of your project:

1spring-boot-intro/ 2├── src/ 3│ ├── main/ 4│ │ ├── kotlin/ 5│ │ │ └── com/ 6│ │ │ └── codesignal/ 7│ │ │ └── MyApplication.kt 8│ │ ├── resources/ 9│ │ └── application.properties 10│ ├── test/ 11│ │ ├── kotlin/ 12│ │ │ └── com/ 13│ │ │ └── codesignal/ 14│ │ │ └── MyApplicationTests.kt 15├── build.gradle.kts

Let's break down the key directories and files:

  • src/main/kotlin: This directory contains your main source code. This is where you write your Kotlin classes and define the core logic of your application.
  • src/main/resources: Holds resources like configuration files (application.properties), static files, and templates. Resources in this directory are included in the classpath.
  • src/test/kotlin: This directory contains your test cases. It mirrors the structure of src/main/kotlin but is specifically for testing your application.

These directories form the backbone of your project, ensuring it is organized and modular.

Important Files At a Glance

Let's take a closer look at some of the essential files in your Spring Boot project:

  1. MyApplication.kt: This is the entry point of the Spring Boot application.
  2. build.gradle.kts: The Gradle build specification file, which contains dependencies and plugins necessary for building the project.
  3. application.properties: Located in src/main/resources, this file is used for configuring various aspects of the application.
  4. MyApplicationTests.kt: Located in src/test/kotlin, this simple test class ensures that the Spring application context loads successfully. You'll add more tests as you develop the application.
Understanding Gradle

Gradle is a versatile build automation tool that streamlines the building, testing, and packaging processes of software projects. While commonly used for Java and Kotlin projects, Gradle supports numerous other languages. Its core functions include:

  • Dependency Management: Gradle automatically retrieves and integrates the libraries your project requires.
  • Code Compilation: It translates your source code into executable code.
  • Test Execution: Gradle runs your tests to verify the correctness of your code.
  • Application Packaging: It assembles your code into a distributable and runnable format.

Think of Gradle as a smart assistant that handles repetitive tasks, so you can focus on writing code.

Exploring the Gradle Build Specification

The build.gradle.kts file is the script used by Gradle to build the project. It is written using Kotlin DSL. This file specifies the project dependencies, plugins, and other configurations. Here's an example build.gradle.kts file for a Spring Boot project:

Kotlin
1plugins { 2 kotlin("jvm") version "1.9.25" 3 kotlin("plugin.spring") version "1.9.25" 4 id("org.springframework.boot") version "3.2.0" 5 id("io.spring.dependency-management") version "1.1.5" 6 kotlin("plugin.jpa") version "1.9.25" 7} 8 9group = "com.codesignal" 10version = "0.0.1-SNAPSHOT" 11 12java { 13 toolchain { 14 languageVersion = JavaLanguageVersion.of(17) 15 } 16} 17 18repositories { 19 mavenCentral() 20} 21 22dependencies { 23 implementation("org.springframework.boot:spring-boot-starter-web") 24 implementation("com.fasterxml.jackson.module:jackson-module-kotlin") 25 implementation("org.jetbrains.kotlin:kotlin-reflect") 26 27 testImplementation("org.springframework.boot:spring-boot-starter-test") 28 testImplementation("org.jetbrains.kotlin:kotlin-test-junit5") 29 testRuntimeOnly("org.junit.platform:junit-platform-launcher") 30} 31 32kotlin { 33 jvmToolchain(17) 34} 35 36tasks.named<Test> { 37 useJUnitPlatform() 38}

Key components:

  • Plugins: Used to add functionality to the build script. The org.springframework.boot plugin is particularly important because it allows you to use Spring Boot without having to specify specific versions for spring dependencies. This ensures that your dependencies are compatible and simplifies the management of library versions. It also provides the gradle bootRun command that lets you run your Spring Boot application from the command line.

  • Dependencies: These specify the libraries required for the project. Notice that the dependencies are mostly "starter" dependencies like spring-boot-starter-web. These starter dependencies are special in that they typically don’t have any library code themselves but instead transitively pull other libraries. This keeps your build file significantly smaller and easier to manage. You can think of your dependencies in terms of capabilities rather than individual library names.

  • Repositories: Locations where Gradle will look for these dependencies. mavenCentral() is a widely used repository that hosts a large number of libraries.

  • Group and Version: These define the naming for the resulting artifact (e.g., JAR file). group sets the base package name, and version specifies the version of the artifact.

  • Source Compatibility: The java { toolchain { languageVersion = JavaLanguageVersion.of(17) } } configuration indicates that Java 17 is the language level used for the Java Virtual Machine (JVM) to compile the Kotlin code. Even though you're writing in Kotlin, the JVM, which executes the compiled bytecode, is specified to use a particular Java version. This is important for ensuring compatibility with JVM features and libraries that require a specific Java version.

  • Kotlin JVM Toolchain: The kotlin { jvmToolchain(17) } line specifies that the Kotlin compiler should target JVM 17 when compiling your Kotlin code. It aligns with the Java toolchain configuration and ensures that your Kotlin code is compatible with the features available in JVM 17. By explicitly setting this, you ensure that the Kotlin code you're writing takes full advantage of the specific JVM version's capabilities and features.

  • Test Configuration: tasks.withType<Test> { useJUnitPlatform() } specifies that JUnit Platform should be used for running the tests. This enables you to leverage modern JUnit 5 features. Don't worry about the tests for now; we'll cover them in detail later in the course path.

Following Gradle conventions ensures your project is well-structured and manageable.

Exploring the Bootstrap Class

The cornerstone of a Spring Boot application is its bootstrap class. In your case, it's named MyApplication.kt. This class contains the main method that Spring Boot uses to start the application. Let's break down the bootstrap class:

Kotlin
1@SpringBootApplication 2class MyApplication 3 4fun main(args: Array<String>) { 5 runApplication<MyApplication>(*args) 6}

The @SpringBootApplication annotation is particularly powerful. You'll delve into it more in later lessons, but for now, understand that this annotation signals Spring Boot to auto-configure the application based on the dependencies and configurations present. This is one of many annotations that Spring relies on heavily to simplify configurations and enhance functionality.

The other crucial component is the main() method. This method serves as the entry point of the application and is executed when the JAR file is run. The line runApplication<MyApplication>(*args) tells Spring Boot to start the application, create the Spring application context, and start the embedded Tomcat server. In most cases, this method will remain boilerplate code across different Spring Boot applications.

Understanding the bootstrap class is essential, as it sets up and runs your Spring Boot application.

Understanding the Application Properties File

The application.properties file is a pivotal configuration file in a Spring Boot project. It is located in the src/main/resources directory and plays a crucial role in configuring various aspects of the application. Let's explore some common configurations that you might specify in this file:

  • Server Port: By default, the embedded Tomcat server listens on port 8080. You can change this by specifying a different port in the application.properties file:

    .properties
    1server.port=8081
  • Logging Level: You can set the logging level to control the verbosity of logs. For example, to set the logging level for the application to DEBUG:

    .properties
    1logging.level.root=DEBUG
  • Database Configuration: If your application interacts with a database, you can define properties like the URL, username, and password:

    .properties
    1spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase 2spring.datasource.username=myusername 3spring.datasource.password=mypassword
  • Custom Application Properties: You can add custom properties for use in your application. These can then be accessed in your code using Spring's @Value annotation or Environment interface.

The application.properties file provides a centralized location for specifying configuration settings, allowing you to externalize configuration and keep your codebase clean and maintainable.

Most Useful Gradle Commands

Now that you're familiar with the project structure and key files, it's important to learn how to manage the application using Gradle. The Gradle CLI provides several commands for building, testing, and managing the project. Here are some of the most commonly used commands:

  • gradle build: Compiles and assembles the project. This command includes running tests as part of the build process.
  • gradle clean: Deletes the build directory to ensure a clean slate for the next build.
  • gradle test: Runs the tests.
  • gradle bootRun: Runs the Spring Boot application.

Ensure you execute these commands from the root directory of your Gradle project, where the build.gradle.kts file is located.

Understanding Tomcat Server

If you're new to web development, you might be accustomed to writing programs that run for a finite duration and then terminate. However, when building a web application, the application needs to run continuously to receive HTTP requests from users and respond to them. Given that Spring Boot is predominantly used for web development, it incorporates an embedded Tomcat server. This server runs your application indefinitely, listening for incoming web requests. By default, the application runs on port 8080. As a result, when you execute the gradle bootRun command, your application doesn't simply run and exit; it starts up and remains active until you manually stop it.

Summary

To wrap up, you explored the standard structure of a Spring Boot project, emphasizing Gradle conventions, and examined the crucial directories and files, including the bootstrap class MyApplication.kt, build.gradle.kts, and application.properties. You discussed the role of the build.gradle.kts file and its components, along with the purpose and annotations of the bootstrap class. You also got familiar with some essential Gradle commands that enable you to run the Spring Boot application or execute tests. This foundational knowledge prepares you to dive deeper into building a Spring Boot application. Happy coding!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.