Sub topic 2
Generating a Spring Boot Project with Spring Initializr
This chapter assumes basic Java, Maven, HTTP, and terminal use. Spring Initializr is a web tool that creates a ready-to-build Spring Boot project from selected options and dependencies.
Generate the project
Open [start.spring.io](https://start.spring.io/) and choose:
- Project: Maven
- Language: Java
- Packaging: Jar
- Java: the JDK version installed locally
- Dependency: Spring Web
Set a group such as com.example and an artifact such as demo. Download the generated ZIP file, extract it, and open the directory in your editor.
The selected dependency is a starter. A starter is a curated group of libraries for a common task. Spring Web supplies Spring MVC and an embedded web server.
Tour of the generated structure
Typical files and directories include:
| Path | Purpose |
|---|---|
| `src/main/java` | Application source code |
| `src/main/resources` | Configuration and other runtime resources |
| `src/test/java` | Test source code |
| `pom.xml` | Maven project definition |
| `mvnw` and `mvnw.cmd` | Maven wrapper scripts |
Keep the main application class near the top package. Spring Boot scans that package and its subpackages for application components.
Read the build file
The pom.xml uses the Spring Boot parent to manage compatible dependency versions. You usually omit versions for Spring-managed dependencies.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.4.0</version>
</parent>
<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>The Spring Boot Maven plugin packages the application as an executable JAR.
The main class
Initializr creates an entry point like this:
package com.example.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);
}
}@SpringBootApplication combines configuration, component scanning, and auto-configuration. Auto-configuration creates common Spring beans when the classpath and settings indicate they are needed. SpringApplication.run creates and starts the application context.
Exercise
Why should a controller usually be placed in a subpackage of the main application class?
Show answer
Component scanning starts at the main class's package and searches its subpackages.