46_Spring Boot快速入门

Spring Boot快速入门

前言

如果你曾经被Spring框架繁琐的XML配置和依赖管理折磨过,那么Spring Boot就是你的救星。Spring Boot基于"约定优于配置"的设计理念,通过自动配置和内嵌服务器,让开发者几乎零配置就能快速搭建一个生产级的Spring应用。

为什么Spring Boot是革命性的? 回想一下传统Spring MVC项目的搭建过程:配置web.xml、spring-mvc.xml、applicationContext.xml,配置DispatcherServlet、视图解析器、静态资源映射,部署到Tomcat……仅仅是让一个Hello World跑起来就需要写几十行XML配置。而Spring Boot只需一个@SpringBootApplication注解和一个main方法,就能直接启动一个完整的Web应用。这就是"约定优于配置"的威力——框架默认已经做好了最优配置,你只需在需要个性化时才做调整。Spring Boot已经是企业级Java开发的事实标准,面试中Spring Boot的自动配置原理几乎是必问题。

本文将从项目创建开始,带你快速体验Spring Boot的优雅开发体验。

一、Spring Boot概述

1.1 为什么选择Spring Boot

传统的Spring应用开发面临以下痛点:

  • 大量XML配置文件
  • 繁琐的依赖管理(版本冲突)
  • 需要单独部署到Tomcat等Servlet容器
  • 各种组件的集成配置复杂

Spring Boot的解决方案:

痛点Spring Boot解决方式
复杂配置自动配置(Auto Configuration)
依赖管理Starter起步依赖
独立部署内嵌Tomcat/Jetty/Undertow
环境切换Profile多环境支持

1.2 Spring Boot核心特性

  • 自动配置:根据类路径和已有配置,自动配置Spring和第三方库
  • Starter起步依赖:一站式引入一组相关的依赖,如 spring-boot-starter-web
  • Actuator监控:生产级应用监控和管理端点
  • 外部化配置:通过properties/YAML文件和命令行参数灵活配置
  • 无代码生成和XML:告别XML配置,纯Java配置

二、第一个Spring Boot项目

2.1 使用Spring Initializr创建

访问 https://start.spring.io,按以下步骤创建:

  1. Project选择:Maven
  2. Language选择:Java
  3. Spring Boot版本选择最新的稳定版(如3.2.x)
  4. 填写项目元数据:
    • Group:com.example
    • Artifact:demo
  5. 添加依赖:Spring WebLombok
  6. 点击Generate下载,解压后用IDEA打开

2.2 项目结构

demo/
├── src/main/java/com/example/demo/
│   └── DemoApplication.java        # 启动类
├── src/main/resources/
│   ├── static/                      # 静态资源
│   ├── templates/                   # 模板文件
│   └── application.properties      # 配置文件
├── src/test/java/
│   └── DemoApplicationTests.java   # 测试类
└── pom.xml

2.3 启动类

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 是一个组合注解,它等价于以下三个注解:

  • @SpringBootConfiguration:标识配置类(等效于@Configuration)
  • @EnableAutoConfiguration:启用自动配置
  • @ComponentScan:组件扫描,自动注册@Component等注解的Bean

三个注解各自的作用

  • @SpringBootConfiguration:本质上就是一个@Configuration注解,让启动类本身成为一个Spring配置类,可以在其中定义@Bean方法
  • @EnableAutoConfiguration:这是最核心的注解。它通过导入AutoConfigurationImportSelector类,读取所有jar包中META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports文件,加载所有自动配置类。这些自动配置类通过@Conditional条件注解判断是否生效
  • @ComponentScan:默认扫描启动类所在包及其子包下的所有组件(@Component、@Service、@Controller等)。这也是为什么其他类不能放在启动类的上级目录——默认扫描范围不包含上级目录

2.4 编写第一个接口

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

@RestController
public class HelloController {
    
    @GetMapping("/hello")
    public String hello(@RequestParam(defaultValue = "World") String name) {
        return "Hello, " + name + "!";
    }
}

运行 DemoApplication 的main方法,访问 http://localhost:8080/hello?name=SpringBoot 即可看到结果。

三、Starter起步依赖

Starter是Spring Boot最核心的设计之一,每种Starter都封装了一组相关的依赖,开发者只需引入一个Starter即可获得完整的特性支持。

3.1 常用Starter

Starter的命名规范:官方Starter以spring-boot-starter-*命名(如spring-boot-starter-web),第三方Starter以*-spring-boot-starter命名(如mybatis-spring-boot-starter)。通过命名就能区分来源,这是Spring Boot的约定之一。记住这个规范对查找和选择依赖很有帮助。

<!-- Web开发 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- 数据访问 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<!-- 安全框架 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

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

<!-- Actuator监控 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

<!-- 邮件 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

<!-- Thymeleaf模板 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

3.2 版本管理

Spring Boot通过parent POM统一管理依赖版本,开发者无需手动指定版本号:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.2.0</version>
</parent>

如果需要使用特定版本的依赖,可以在properties中覆盖:

<properties>
    <mysql.version>8.0.33</mysql.version>
</properties>

四、配置文件

4.1 application.properties

properties与yml的选择:两者功能上等价,但yml格式更简洁、层次分明。在实际项目中,推荐使用yml——它可以减少重复前缀,结构一目了然。但要注意yml对缩进非常敏感,只能用空格不能用Tab,缩进层级必须严格一致,否则解析失败。

# 服务端口
server.port=8081

# 应用名称
spring.application.name=demo-app

# 数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# JPA配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

# 日志级别
logging.level.com.example=debug
logging.file.path=./logs

4.2 application.yml(推荐)

YAML格式更加简洁、层次分明:

server:
  port: 8081

spring:
  application:
    name: demo-app
  datasource:
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true

logging:
  level:
    com.example: debug
  file:
    path: ./logs

4.3 多环境配置

# application.yml - 公共配置
spring:
  application:
    name: demo-app

---
# application-dev.yml - 开发环境
spring:
  config:
    activate:
      on-profile: dev
  datasource:
    url: jdbc:mysql://localhost:3306/dev_db
    username: root
    password: dev123

---
# application-prod.yml - 生产环境
spring:
  config:
    activate:
      on-profile: prod
  datasource:
    url: jdbc:mysql://prod-server:3306/prod_db
    username: admin
    password: ${DB_PASSWORD}  # 使用环境变量

激活指定环境:

# application.properties
spring.profiles.active=dev

或在启动命令中指定:

java -jar demo.jar --spring.profiles.active=prod

4.4 配置绑定

使用 @ConfigurationProperties 将配置绑定到Java对象:

@Component
@ConfigurationProperties(prefix = "app.oss")
@Data
public class OssConfig {
    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;
}
app:
  oss:
    endpoint: oss-cn-hangzhou.aliyuncs.com
    access-key-id: your-key
    access-key-secret: your-secret
    bucket-name: my-bucket

4.5 自定义属性与随机值

app:
  name: MyApp
  version: 1.0.0
  secret: ${random.uuid}
  port: ${random.int(1024,65535)}
@Value("${app.name}")
private String appName;

@Value("${app.secret}")
private String secret;

五、自动配置原理

Spring Boot自动配置的核心是 @EnableAutoConfiguration,它通过 spring-boot-autoconfigure 包中的 META-INF/spring.factories 文件注册了大量的自动配置类。

自动配置是如何"按需"的? 这是面试的高频问题。自动配置类的核心设计模式是"条件注解"。例如,DataSourceAutoConfiguration会检查:1)类路径中是否有DataSource类(@ConditionalOnClass);2)容器中是否已经有用户自定义的DataSource Bean(@ConditionalOnMissingBean)。只有两个条件都满足时,自动配置才会创建默认的DataSource。这种设计保证了"用户自定义优先"的原则——你配置的Bean会覆盖自动配置。

自动配置的流程:

  1. Spring Boot启动时加载所有 XxxAutoConfiguration
  2. 通过 @Conditional 系列注解判断配置是否生效
  3. 如果类路径中存在对应的类且缺少用户自定义配置,则自动配置生效

常见条件注解:

注解说明
@ConditionalOnClass类路径中存在指定类时生效
@ConditionalOnMissingBean容器中不存在指定Bean时生效
@ConditionalOnProperty配置文件中存在指定属性时生效
@ConditionalOnBean容器中存在指定Bean时生效
@ConditionalOnMissingClass类路径中缺失指定类时生效
@ConditionalOnWebApplication是Web应用时生效

六、Spring Boot打包与部署

# 打包
mvn clean package -DskipTests

# 运行
java -jar target/demo-1.0-SNAPSHOT.jar

# 带参数运行
java -jar demo.jar --server.port=9090

总结

本文从创建第一个Spring Boot项目开始,介绍了Starter依赖管理、配置文件使用以及自动配置原理等核心内容。Spring Boot让Java开发变得前所未有的简单——不用写一行XML配置,就能快速搭建一个企业级应用。掌握Spring Boot是进入现代Java开发的必经之路。

面试高频总结

  1. Spring Boot核心特性:自动配置、Starter、内嵌服务器、Actuator监控
  2. @SpringBootApplication本质:@Configuration + @EnableAutoConfiguration + @ComponentScan
  3. 自动配置原理:通过@Conditional条件注解(OnClass/OnMissingBean等)按需加载
  4. Starter命名规范:官方spring-boot-starter-、第三方-spring-boot-starter
  5. 多环境切换:application-{profile}.yml + spring.profiles.active

✅ 亮点总结

  • @SpringBootApplication组合注解:一键启用自动配置、组件扫描和配置类功能
  • Starter起步依赖:spring-boot-starter-web/webflux/data-jpa等,一个依赖引入全套组件
  • application.yml多环境配置:dev/test/prod通过spring.profiles.active灵活切换
  • @ConfigurationProperties类型安全的配置绑定,替换@Value的零散注入
  • 自动配置原理:@ConditionalOnClass/MissingBean条件注解按需加载,无需手动配置

适用场景

  • 快速搭建微服务项目骨架,5分钟内启动一个可运行的Web服务
  • 开发/测试/生产多环境配置隔离,数据库密码等敏感信息使用环境变量
  • 创建独立可执行的Fat Jar,配合Docker实现一键部署

扩展方向

  • 学习Spring Boot Actuator实现应用健康检查、Metrics指标收集和运维监控
  • 了解自定义Starter的开发流程,封装公司内部通用组件为Starter
  • 推荐阅读下一篇文章:[Spring Boot整合MyBatis](./47_Spring Boot整合MyBatis),实现数据库CRUD操作
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值