SpringBoot详细配置与启动指南

1. SpringBoot简介

Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Spring Boot致力于在蓬勃发展的快速应用开发领域成为领导者。

1.1 SpringBoot的核心特性

  • 自动配置:SpringBoot会根据类路径中的jar包、类,为jar包里的类自动配置Bean
  • 起步依赖:告诉SpringBoot需要什么功能,它就会引入需要的库
  • 命令行界面:这是SpringBoot的可选特性,主要针对Groovy语言
  • Actuator:让你能够深入运行中的SpringBoot应用程序,一探究竟

1.2 为什么选择SpringBoot

  • 简化配置,专注于业务
  • 内嵌服务器,无需部署WAR文件
  • 提供生产级别的监控、健康检查及外部化配置
  • 无代码生成和XML配置要求

2. SpringBoot项目结构

一个标准的SpringBoot项目结构如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
myproject/
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── example/
│ │ │ └── myproject/
│ │ │ ├── MyprojectApplication.java
│ │ │ ├── controller/
│ │ │ ├── service/
│ │ │ ├── repository/
│ │ │ └── model/
│ │ └── resources/
│ │ ├── application.properties (或 application.yml)
│ │ ├── static/
│ │ └── templates/
│ └── test/
│ └── java/
│ └── com/
│ └── example/
│ └── myproject/
│ └── MyprojectApplicationTests.java
├── pom.xml (Maven项目) 或 build.gradle (Gradle项目)
└── README.md

3. SpringBoot项目创建

3.1 使用Spring Initializr创建

  1. 访问 Spring Initializr
  2. 选择构建工具(Maven/Gradle)
  3. 选择语言(Java/Kotlin/Groovy)
  4. 选择Spring Boot版本
  5. 填写项目元数据(Group、Artifact等)
  6. 选择依赖(如Web、JPA、Security等)
  7. 点击”Generate”下载项目压缩包
  8. 解压并导入IDE

3.2 使用IDE创建

IntelliJ IDEA

  1. 点击 File -> New -> Project
  2. 选择 Spring Initializr
  3. 配置项目信息
  4. 选择依赖
  5. 点击 Finish

Eclipse/STS

  1. 点击 File -> New -> Spring Starter Project
  2. 配置项目信息
  3. 选择依赖
  4. 点击 Finish

3.3 使用命令行创建

使用Spring Boot CLI:

1
spring init --dependencies=web,data-jpa myproject

4. SpringBoot核心配置

4.1 配置文件类型

SpringBoot支持多种配置文件格式:

  • application.properties:键值对形式
  • application.yml:YAML格式,层次结构更清晰
  • application.yaml:同上,扩展名不同

配置文件默认位置:

  • src/main/resources/application.properties
  • src/main/resources/application.yml

4.2 配置文件优先级

  1. 命令行参数
  2. java:comp/env里的JNDI属性
  3. JVM系统属性
  4. 操作系统环境变量
  5. RandomValuePropertySource配置的random.*属性值
  6. jar包外部的application-{profile}.properties或application.yml(带spring.profile)配置文件
  7. jar包内部的application-{profile}.properties或application.yml(带spring.profile)配置文件
  8. jar包外部的application.properties或application.yml(不带spring.profile)配置文件
  9. jar包内部的application.properties或application.yml(不带spring.profile)配置文件

4.3 YAML配置示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
server:
port: 8080
servlet:
context-path: /api

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

logging:
level:
root: INFO
org.springframework.web: DEBUG
com.example.myproject: DEBUG

4.4 Properties配置示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 服务器配置
server.port=8080
server.servlet.context-path=/api

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

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

# 日志配置
logging.level.root=INFO
logging.level.org.springframework.web=DEBUG
logging.level.com.example.myproject=DEBUG

4.5 多环境配置

SpringBoot支持不同环境下使用不同的配置文件,通过spring.profiles.active属性来激活。

4.5.1 创建多环境配置文件

  • application-dev.yml:开发环境
  • application-test.yml:测试环境
  • application-prod.yml:生产环境

4.5.2 激活指定环境

在application.yml中:

1
2
3
spring:
profiles:
active: dev

或者通过命令行参数:

1
java -jar myapp.jar --spring.profiles.active=prod

5. SpringBoot常用配置详解

5.1 服务器配置

1
2
3
4
5
6
7
8
9
10
11
server:
port: 8080 # 服务端口
servlet:
context-path: /api # 应用上下文路径
session:
timeout: 30m # Session超时时间
tomcat:
max-threads: 200 # 最大工作线程数
min-spare-threads: 10 # 最小工作线程数
max-connections: 10000 # 最大连接数
connection-timeout: 5000 # 连接超时时间(ms)

5.2 数据源配置

1
2
3
4
5
6
7
8
9
10
11
12
13
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC
username: root
password: password
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.zaxxer.hikari.HikariDataSource # 使用Hikari连接池
hikari:
maximum-pool-size: 20 # 最大连接数
minimum-idle: 5 # 最小空闲连接
idle-timeout: 30000 # 空闲连接超时时间(ms)
connection-timeout: 30000 # 连接超时时间(ms)
max-lifetime: 1800000 # 连接最大生命周期(ms)

5.3 JPA配置

1
2
3
4
5
6
7
8
9
10
11
spring:
jpa:
database-platform: org.hibernate.dialect.MySQL8Dialect
hibernate:
ddl-auto: update # 数据库schema更新策略
show-sql: true # 显示SQL语句
properties:
hibernate:
format_sql: true # 格式化SQL
use_sql_comments: true # 使用SQL注释
open-in-view: false # 禁用Open Session in View

5.4 Redis配置

1
2
3
4
5
6
7
8
9
10
11
12
13
spring:
redis:
host: localhost
port: 6379
password:
database: 0 # 使用的数据库索引
timeout: 10000 # 连接超时时间(ms)
lettuce: # 使用Lettuce客户端
pool:
max-active: 8 # 最大连接数
max-idle: 8 # 最大空闲连接
min-idle: 0 # 最小空闲连接
max-wait: -1 # 连接等待时间(ms)

5.5 缓存配置

1
2
3
4
5
spring:
cache:
type: caffeine # 缓存类型
caffeine:
spec: maximumSize=500,expireAfterAccess=600s

5.6 消息队列配置(RabbitMQ)

1
2
3
4
5
6
7
8
9
10
11
12
spring:
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
virtual-host: /
listener:
simple:
concurrency: 5 # 最小消费者数量
max-concurrency: 10 # 最大消费者数量
prefetch: 1 # 每次从队列获取的消息数量

5.7 日志配置

1
2
3
4
5
6
7
8
9
10
11
logging:
level:
root: INFO # 根日志级别
org.springframework.web: DEBUG # Spring Web日志级别
org.hibernate: ERROR # Hibernate日志级别
com.example.myproject: DEBUG # 应用日志级别
file:
name: logs/application.log # 日志文件名
pattern:
console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"
file: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"

5.8 安全配置

1
2
3
4
5
6
spring:
security:
user:
name: admin # 默认用户名
password: admin # 默认密码
roles: ADMIN # 默认角色

5.9 文件上传配置

1
2
3
4
5
6
7
spring:
servlet:
multipart:
enabled: true # 启用文件上传
file-size-threshold: 2KB # 文件写入磁盘的阈值
max-file-size: 200MB # 最大文件大小
max-request-size: 215MB # 最大请求大小

5.10 国际化配置

1
2
3
4
5
spring:
messages:
basename: i18n/messages # 国际化资源文件基础名
encoding: UTF-8 # 编码
cache-duration: 3600 # 缓存时间(秒)

6. SpringBoot启动原理

6.1 启动流程

  1. 创建SpringApplication对象

    • 推断应用类型(SERVLET、REACTIVE、NONE)
    • 查找并加载所有可用的初始化器
    • 查找所有的应用程序监听器
    • 推断并设置main方法的定义类
  2. 运行SpringApplication

    • 启动计时器
    • 发布应用启动事件
    • 准备环境
    • 创建上下文对象
    • 预处理上下文
    • 刷新上下文
    • 后置处理上下文
    • 发布应用已启动事件
    • 执行runners

6.2 自动配置原理

SpringBoot自动配置是通过@EnableAutoConfiguration注解实现的,其核心步骤如下:

  1. @SpringBootApplication:包含了@EnableAutoConfiguration
  2. @EnableAutoConfiguration:导入AutoConfigurationImportSelector
  3. AutoConfigurationImportSelector
    • 加载META-INF/spring.factories中的配置类
    • 过滤不符合条件的配置类
    • 将符合条件的配置类导入Spring容器

6.3 条件注解

SpringBoot通过条件注解来决定是否创建某个Bean:

  • @ConditionalOnClass:当类路径下有指定的类时
  • @ConditionalOnMissingClass:当类路径下没有指定的类时
  • @ConditionalOnBean:当容器中有指定的Bean时
  • @ConditionalOnMissingBean:当容器中没有指定的Bean时
  • @ConditionalOnProperty:当指定的属性有指定的值时
  • @ConditionalOnResource:当类路径下有指定的资源时
  • @ConditionalOnWebApplication:当前项目是Web项目时
  • @ConditionalOnNotWebApplication:当前项目不是Web项目时
  • @ConditionalOnExpression:基于SpEL表达式的条件判断

7. SpringBoot启动类详解

7.1 基本启动类

1
2
3
4
5
6
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}

7.2 自定义SpringApplication

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication application = new SpringApplication(MyApplication.class);

// 禁用banner
application.setBannerMode(Banner.Mode.OFF);

// 设置为非web环境
application.setWebApplicationType(WebApplicationType.NONE);

// 添加监听器
application.addListeners(new ApplicationStartingListener());

// 设置额外的配置文件
application.setAdditionalProfiles("prod");

// 运行应用
application.run(args);
}
}

7.3 使用Builder API

1
2
3
4
5
6
7
8
9
10
11
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
new SpringApplicationBuilder()
.sources(MyApplication.class)
.bannerMode(Banner.Mode.OFF)
.web(WebApplicationType.SERVLET)
.profiles("dev")
.run(args);
}
}

7.4 命令行参数

1
2
3
4
5
6
7
8
9
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
// 将命令行参数转换为属性
SpringApplication app = new SpringApplication(MyApplication.class);
app.setAddCommandLineProperties(true);
app.run(args);
}
}

7.5 ApplicationRunner和CommandLineRunner

这两个接口可以在SpringBoot启动后执行特定的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}

@Bean
public CommandLineRunner commandLineRunner() {
return args -> {
System.out.println("应用启动后执行CommandLineRunner...");
// 可以访问命令行参数
for (String arg : args) {
System.out.println(arg);
}
};
}

@Bean
public ApplicationRunner applicationRunner() {
return args -> {
System.out.println("应用启动后执行ApplicationRunner...");
// 可以访问选项和非选项参数
System.out.println("选项参数: " + args.getOptionNames());
System.out.println("非选项参数: " + args.getNonOptionArgs());
};
}
}

8. SpringBoot常用注解

8.1 核心注解

  • @SpringBootApplication:组合注解,包含@Configuration、@EnableAutoConfiguration和@ComponentScan
  • @EnableAutoConfiguration:启用SpringBoot的自动配置机制
  • @Configuration:标记类为配置类
  • @ComponentScan:指定要扫描的包

8.2 Web相关注解

  • @Controller:标记类为控制器
  • @RestController:@Controller + @ResponseBody
  • @RequestMapping:映射请求路径
  • @GetMapping:映射GET请求
  • @PostMapping:映射POST请求
  • @PutMapping:映射PUT请求
  • @DeleteMapping:映射DELETE请求
  • @RequestParam:绑定请求参数
  • @PathVariable:绑定路径变量
  • @RequestBody:绑定请求体
  • @ResponseBody:将返回值序列化为响应体

8.3 数据访问注解

  • @Repository:标记类为数据访问组件
  • @Entity:标记类为JPA实体
  • @Table:指定实体对应的表
  • @Id:标记字段为主键
  • @GeneratedValue:指定主键生成策略
  • @Column:指定字段对应的列
  • @Transactional:声明事务

8.4 服务层注解

  • @Service:标记类为服务组件
  • @Autowired:自动装配依赖
  • @Qualifier:指定要装配的Bean
  • @Value:注入配置属性
  • @ConfigurationProperties:绑定配置属性到类

8.5 条件注解

  • @Conditional:基于条件创建Bean
  • @ConditionalOnBean:当存在指定Bean时
  • @ConditionalOnMissingBean:当不存在指定Bean时
  • @ConditionalOnClass:当存在指定类时
  • @ConditionalOnMissingClass:当不存在指定类时
  • @ConditionalOnProperty:当存在指定属性时
  • @ConditionalOnWebApplication:当是Web应用时
  • @ConditionalOnNotWebApplication:当不是Web应用时

9. SpringBoot启动方式

9.1 IDE中启动

在IDE中直接运行主类的main方法。

9.2 命令行启动

使用Maven

1
2
3
4
5
6
7
8
# 使用Maven插件启动
mvn spring-boot:run

# 指定配置文件
mvn spring-boot:run -Dspring.profiles.active=prod

# 指定JVM参数
mvn spring-boot:run -Dspring-boot.run.jvmArguments="-Xms512m -Xmx1024m"

使用Gradle

1
2
3
4
5
# 使用Gradle插件启动
gradle bootRun

# 指定配置文件
gradle bootRun --args='--spring.profiles.active=prod'

使用打包后的JAR

1
2
3
4
5
6
7
8
9
10
11
# 打包
mvn clean package

# 运行JAR
java -jar target/myapp-0.0.1-SNAPSHOT.jar

# 指定配置文件
java -jar target/myapp-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod

# 指定JVM参数
java -Xms512m -Xmx1024m -jar target/myapp-0.0.1-SNAPSHOT.jar

9.3 使用Spring Boot CLI

1
2
3
# 安装Spring Boot CLI
# 运行Groovy脚本
spring run app.groovy

9.4 作为系统服务

Linux (systemd)

创建服务文件 /etc/systemd/system/myapp.service

1
2
3
4
5
6
7
8
9
10
11
[Unit]
Description=My Spring Boot Application
After=syslog.target

[Service]
User=myapp
ExecStart=/usr/bin/java -jar /path/to/myapp.jar
SuccessExitStatus=143

[Install]
WantedBy=multi-user.target

启动服务:

1
2
sudo systemctl enable myapp.service
sudo systemctl start myapp.service

Windows

使用winsw将应用注册为Windows服务。

10. SpringBoot应用监控与管理

10.1 Actuator

Spring Boot Actuator提供了生产级别的监控和管理功能。

10.1.1 添加依赖

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

10.1.2 配置Actuator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
management:
endpoints:
web:
exposure:
include: "*" # 暴露所有端点
base-path: /actuator # 端点基础路径
endpoint:
health:
show-details: always # 显示详细健康信息
shutdown:
enabled: true # 启用关闭端点
info:
env:
enabled: true # 启用环境信息

10.1.3 常用端点

  • /actuator/health:应用健康状态
  • /actuator/info:应用信息
  • /actuator/metrics:应用指标
  • /actuator/env:环境变量
  • /actuator/loggers:日志配置
  • /actuator/mappings:请求映射
  • /actuator/beans:Spring Bean信息
  • /actuator/shutdown:关闭应用(POST请求)

10.2 Spring Boot Admin

Spring Boot Admin是一个Web应用,用于管理和监控Spring Boot应用。

10.2.1 创建Admin Server

1
2
3
4
5
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-server</artifactId>
<version>2.7.0</version>
</dependency>
1
2
3
4
5
6
7
@SpringBootApplication
@EnableAdminServer
public class AdminServerApplication {
public static void main(String[] args) {
SpringApplication.run(AdminServerApplication.class, args);
}
}

10.2.2 配置客户端

1
2
3
4
5
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>2.7.0</version>
</dependency>
1
2
3
4
5
6
7
8
9
10
spring:
boot:
admin:
client:
url: http://localhost:8080 # Admin Server地址
instance:
name: ${spring.application.name}
metadata:
tags:
environment: production

11. SpringBoot最佳实践

11.1 项目结构

1
2
3
4
5
6
7
8
9
10
11
com.example.myproject
├── config # 配置类
├── controller # 控制器
├── dto # 数据传输对象
├── entity # 实体类
├── repository # 数据访问层
├── service # 服务层
│ ├── impl # 服务实现
├── exception # 自定义异常
├── util # 工具类
└── Application.java # 启动类

11.2 配置管理

  • 使用YAML格式配置文件,层次结构更清晰
  • 使用@ConfigurationProperties绑定配置到类
  • 敏感信息使用环境变量或外部配置

11.3 异常处理

使用全局异常处理器:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@RestControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleException(Exception ex) {
ErrorResponse error = new ErrorResponse(
HttpStatus.INTERNAL_SERVER_ERROR.value(),
"服务器内部错误",
ex.getMessage()
);
return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
}

@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorResponse> handleResourceNotFoundException(ResourceNotFoundException ex) {
ErrorResponse error = new ErrorResponse(
HttpStatus.NOT_FOUND.value(),
"资源不存在",
ex.getMessage()
);
return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
}
}

11.4 API文档

使用Springfox Swagger:

1
2
3
4
5
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.myproject.controller"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}

private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("My API Documentation")
.description("API documentation for My Project")
.version("1.0.0")
.build();
}
}

11.5 测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@SpringBootTest
class MyServiceTest {

@Autowired
private MyService myService;

@MockBean
private MyRepository myRepository;

@Test
void testGetById() {
// 准备测试数据
MyEntity entity = new MyEntity();
entity.setId(1L);
entity.setName("Test");

// 模拟repository行为
when(myRepository.findById(1L)).thenReturn(Optional.of(entity));

// 执行测试
MyDto result = myService.getById(1L);

// 验证结果
assertNotNull(result);
assertEquals(1L, result.getId());
assertEquals("Test", result.getName());

// 验证repository方法被调用
verify(myRepository).findById(1L);
}
}

12. 总结

SpringBoot通过约定大于配置的理念,大大简化了Spring应用的开发。本文详细介绍了SpringBoot的配置和启动方式,包括:

  1. SpringBoot的核心特性和优势
  2. 项目结构和创建方式
  3. 核心配置文件和常用配置项
  4. 启动原理和自动配置机制
  5. 启动类详解和启动方式
  6. 常用注解和最佳实践

通过掌握这些知识,开发者可以更高效地使用SpringBoot开发企业级应用。

参考资料

  1. Spring Boot官方文档
  2. Spring Boot GitHub仓库
  3. Spring Initializr
  4. Spring Boot Actuator文档
  5. Spring Boot Admin