乐途乐途
主页
  • 计算机基础

    • TCP/IP
    • Linux
    • HTTP
  • 数据库

    • SQL
    • MySQL 5.7
  • 编程语言

    • C
    • C++
    • Java SE
    • Python2
    • Python3
  • 数据格式

    • JSON
    • XML
  • 认证与安全

    • JWT
  • 工具

    • Markdown
  • Git

    • GitFlow
  • Quartz

    • Quartz
  • Java

    • Maven 入门
    • Maven 进阶
    • MyBatis
    • Spring
    • Spring MVC
  • Java

    • Spring Boot
    • Spring Cloud
    • Spring Cloud Alibaba
    • Spring Security
    • Spring AI
    • Spring Batch
    • Kafka
    • Java 设计模式
  • 缓存

    • Redis
  • 搜索引擎

    • Elasticsearch
  • 分布式协调

    • ZooKeeper
联系
阿里云
主页
  • 计算机基础

    • TCP/IP
    • Linux
    • HTTP
  • 数据库

    • SQL
    • MySQL 5.7
  • 编程语言

    • C
    • C++
    • Java SE
    • Python2
    • Python3
  • 数据格式

    • JSON
    • XML
  • 认证与安全

    • JWT
  • 工具

    • Markdown
  • Git

    • GitFlow
  • Quartz

    • Quartz
  • Java

    • Maven 入门
    • Maven 进阶
    • MyBatis
    • Spring
    • Spring MVC
  • Java

    • Spring Boot
    • Spring Cloud
    • Spring Cloud Alibaba
    • Spring Security
    • Spring AI
    • Spring Batch
    • Kafka
    • Java 设计模式
  • 缓存

    • Redis
  • 搜索引擎

    • Elasticsearch
  • 分布式协调

    • ZooKeeper
联系
阿里云
  • 学习路径
  • 第1章 Spring Boot 概述

    • 章节导读:Spring Boot概述与核心理念
    • Spring Boot是什么
    • Spring Boot与Spring Framework的关系
    • 约定优于配置
  • 第2章 快速入门与第一个应用

    • 章节导读:快速入门与第一个应用
    • SpringApplication
    • 第一个Spring Boot应用
  • 第3章 起步依赖与版本管理

    • 章节导读:起步依赖与版本管理
    • 起步依赖
    • BOM版本管理
  • 第4章 自动配置原理

    • 章节导读:自动配置原理
    • 自动配置原理
    • AutoConfigurationImportSelector
    • 自动配置报告
  • 第5章 核心注解

    • 章节导读:核心注解
    • @SpringBootApplication
    • @EnableAutoConfiguration
    • @ConditionalOnClass
    • @ConditionalOnMissingBean
    • @ConditionalOnBean
    • @ConditionalOnProperty
  • 第6章 外部化配置与属性绑定

    • 章节导读:外部化配置与属性绑定
    • 外部化配置
    • @ConfigurationProperties
    • @Value
    • 配置属性优先级
  • 第7章 Profile 与环境切换

    • 章节导读:Profile与环境切换
    • @Profile
    • 多环境配置文件
  • 第8章 内嵌服务器与部署

    • 章节导读:内嵌服务器与部署
    • 内嵌服务器
    • Fat Jar
  • 第9章 Actuator 与监控

    • 章节导读:Actuator与监控
    • Actuator Health
    • Actuator Info
    • Actuator Metrics
    • 自定义Endpoint
    • 自定义HealthIndicator
  • 第10章 开发工具与最佳实践

    • 章节导读:开发工具与最佳实践
    • Banner自定义
    • 热部署

一句话定位:本章手把手带你从 start.spring.io 创建广州飞翔科技的学生成绩管理系统,解读 pom.xml 结构、主类、统一 YAML 配置和启动日志,完成从"零项目"到"可运行应用"的完整跨越。


定义与作用

"第一个 Spring Boot 应用"不是讲某个具体注解或类,而是整个项目的最小可运行骨架。它包含:

组成部分作用传统 SSM 的对比
start.spring.io 生成的项目结构标准 Maven 目录、.gitignore、主类、测试类、resources手动创建目录结构,易遗漏
pom.xml + spring-boot-starter-parent统一依赖版本、打包插件、资源过滤手动对齐 Spring + Jackson + Tomcat 版本
主启动类 + @SpringBootApplication自动配置、组件扫描、配置类三合一手写 web.xml + applicationContext.xml
application.yml统一外部化配置,覆盖自动配置默认值分散的 jdbc.properties、log4j.properties
启动日志验证自动配置是否生效、容器是否就绪无统一日志,需自行检查服务器日志

适用位置与常用属性

本节讲解的是项目骨架,而非单个注解。各组成部分的位置如下:

文件/目录标准位置说明
pom.xml项目根目录Maven 构建配置,继承 spring-boot-starter-parent
src/main/java/com/feixiang/student/Java 源码根包结构必须与 groupId + artifactId 对应
StudentManagementApplication.java上述包根主启动类,必须放在根包(如 com.feixiang.student)
src/main/resources/application.ymlResources 根统一配置文件,YAML 格式
src/main/resources/static/Resources 子目录静态资源(HTML、JS、CSS)默认映射
src/test/java/测试源码根测试类位置,@SpringBootTest 自动加载完整上下文

核心原理

从项目生成到应用就绪的完整链路

pom.xml 的依赖传递关系


完整示例

场景说明

飞翔科技后端开发小崔需要从零搭建学生成绩管理系统。架构师白歌要求:项目使用 Spring Boot 2.7.18,包名为 com.feixiang.student,数据库为 student_db,启动后能在控制台看到明确的就绪状态。

操作前:空目录(无项目)

小崔的桌面上只有一个空文件夹 student-management/,没有任何代码文件。

使用 Spring Initializr 和 Spring Boot 的完整步骤

步骤1:在 start.spring.io 生成项目

访问 https://start.spring.io,配置如下:

选项值
ProjectMaven
LanguageJava
Spring Boot2.7.18
Project Metadata - Groupcom.feixiang
Project Metadata - Artifactstudent-management
Project Metadata - Namestudent-management
Project Metadata - Package namecom.feixiang.student
Project Metadata - PackagingJar
Project Metadata - Java8
DependenciesSpring Web, Spring Data JDBC, MySQL Driver

点击 "Generate",下载 student-management.zip 并解压。

步骤2:生成的 pom.xml 结构解读

<?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>

    <!-- 父POM:统一版本管理和插件配置 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.18</version>
        <relativePath/>
    </parent>

    <groupId>com.feixiang</groupId>
    <artifactId>student-management</artifactId>
    <version>1.0.0</version>
    <name>student-management</name>
    <description>广州飞翔科技 - 学生成绩管理系统</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!-- Web 开发:包含 Spring MVC + Tomcat + Jackson -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- JDBC 数据访问:包含 JdbcTemplate + HikariCP -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <!-- MySQL 驱动:runtime 作用域,编译期不需要,运行时需要 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!-- 测试 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!-- Spring Boot 打包插件:将项目打包为可执行 Fat JAR -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

关键观察:所有依赖都没有 <version> 节点。spring-boot-starter-parent 的 spring-boot-dependencies BOM 已经锁定了 Spring MVC 5.3.27、Tomcat 9.0.75、Jackson 2.13.5、HikariCP 4.0.3、MySQL 8.0.x 的兼容版本。

步骤3:主启动类

package com.feixiang.student;

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

/**
 * 广州飞翔科技 - 学生成绩管理系统启动类
 * @author 小崔
 * @since 2024
 */
@SpringBootApplication
public class StudentManagementApplication {
    public static void main(String[] args) {
        SpringApplication.run(StudentManagementApplication.class, args);
    }
}

启动类位于 com.feixiang.student 根包,确保 @ComponentScan 能扫描到 service、repository、controller 等子包。

步骤4:统一 YAML 配置

src/main/resources/application.yml:

spring:
  application:
    name: student-management
  datasource:
    url: jdbc:mysql://localhost:3306/student_db?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver

server:
  port: 8080
  servlet:
    context-path: /api

logging:
  level:
    com.feixiang.student: debug

统一使用 YAML 格式(而非 .properties),层次结构清晰。context-path: /api 表示所有接口前缀为 /api。

步骤5:业务组件验证扫描

package com.feixiang.student.service;

import org.springframework.stereotype.Service;

@Service
public class StudentService {
    public String queryScore(String studentId) {
        return "学生 " + studentId + " 的成绩查询结果";
    }
}

操作后运行结果及分析

在 IDEA 中右键运行 StudentManagementApplication,或命令行执行:

mvn spring-boot:run

启动日志关键片段:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::       (v2.7.18)

2024-05-20 09:30:10.123  INFO 12345 --- [main] c.f.s.StudentManagementApplication : Starting StudentManagementApplication using Java 1.8
2024-05-20 09:30:10.456  INFO 12345 --- [main] c.f.s.StudentManagementApplication : No active profile set, falling back to default profiles: default
2024-05-20 09:30:11.789  INFO 12345 --- [main] o.s.b.w.e.t.TomcatWebServer          : Tomcat initialized with port(s): 8080 (http)
2024-05-20 09:30:12.012  INFO 12345 --- [main] o.s.b.w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1234 ms
2024-05-20 09:30:12.345  INFO 12345 --- [main] com.zaxxer.hikari.HikariDataSource   : HikariPool-1 - Starting...
2024-05-20 09:30:12.567  INFO 12345 --- [main] com.zaxxer.hikari.HikariDataSource   : HikariPool-1 - Start completed
2024-05-20 09:30:12.890  INFO 12345 --- [main] o.s.b.w.e.t.TomcatWebServer          : Tomcat started on port(s): 8080 (http) with context path '/api'
2024-05-20 09:30:13.001  INFO 12345 --- [main] c.f.s.StudentManagementApplication : Started StudentManagementApplication in 2.987 seconds (JVM running for 3.456)

日志解读:

日志行含义验证了什么
Starting ... using Java 1.8应用开始启动,使用 JDK 8环境正确
No active profile set未显式激活 Profile,使用 default配置加载正常
Tomcat initialized with port(s): 8080内嵌 Tomcat 初始化,监听 8080Web 环境自动配置生效
Root WebApplicationContext: initialization completedSpring 容器刷新完成IoC 容器就绪(详见 Spring Core 教程)
HikariPool-1 - Starting...连接池启动DataSourceAutoConfiguration 生效
context path '/api'全局前缀 /api 生效server.servlet.context-path 配置生效
Started in 2.987 seconds总启动耗时性能基准

小崔成功启动了第一个 Spring Boot 应用!从 start.spring.io 到控制台出现 Started,全程不到 5 分钟。


易错场景与面试考点

易错场景:启动类放错包导致组件扫描遗漏

小崔曾把启动类放在 com.feixiang.student.config 子包中,而 StudentService 在 com.feixiang.student.service 包中。

错误示范:

package com.feixiang.student.config;  // ← 错误:放在子包中

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

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

后果:@ComponentScan 默认扫描 com.feixiang.student.config 及其子包。com.feixiang.student.service 与 config 是同级包,不在扫描范围内。StudentService、StudentRepository 等全部遗漏。启动后访问接口报 404 或 NoSuchBeanDefinitionException,小崔排查了半小时才发现是包结构问题。

正确做法:

package com.feixiang.student;  // ← 正确:放在根包

@SpringBootApplication
public class StudentManagementApplication { ... }

或者显式指定扫描范围:

@SpringBootApplication(scanBasePackages = "com.feixiang")
public class StudentManagementApplication { ... }

面试考点

Q:Spring Initializr 生成的 pom.xml 为什么所有依赖都没有 version?

因为继承了 spring-boot-starter-parent,其内部引入了 spring-boot-dependencies BOM(Bill of Materials),通过 <dependencyManagement> 统一锁定了所有 Starter 的传递依赖版本。开发者无需手动管理版本号,避免版本冲突。

Q:application.yml 和 application.properties 有什么区别?本教程为什么统一使用 YAML?

两者功能等价,都是 Spring Boot 的外部化配置文件。YAML 的优势在于:层次结构清晰(缩进表示层级)、支持多文档(--- 分隔,适合多 Profile)、可读性更好。本教程统一使用 application.yml 是飞翔科技的团队规范。

Q:启动日志中 HikariPool-1 - Start completed 说明什么?

说明 DataSourceAutoConfiguration 已生效。Spring Boot 检测到类路径存在 spring-jdbc 和 HikariCP,且 application.yml 中配置了 spring.datasource.url,于是自动创建 HikariDataSource 并初始化连接池。如果没有这个日志,说明数据源自动配置未触发,需检查依赖和配置。

Q:mvn spring-boot:run 和 java -jar 有什么区别?

mvn spring-boot:run 是开发阶段使用,由 spring-boot-maven-plugin 启动,支持 DevTools 热重启,但依赖 Maven 和本地 .m2 仓库;java -jar target/student-management-1.0.0.jar 是生产部署方式,运行的是 Fat JAR,包含所有依赖,无需 Maven 环境。

上一页
SpringApplication