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创建
- 访问 Spring Initializr
- 选择构建工具(Maven/Gradle)
- 选择语言(Java/Kotlin/Groovy)
- 选择Spring Boot版本
- 填写项目元数据(Group、Artifact等)
- 选择依赖(如Web、JPA、Security等)
- 点击”Generate”下载项目压缩包
- 解压并导入IDE
3.2 使用IDE创建
IntelliJ IDEA
- 点击 File -> New -> Project
- 选择 Spring Initializr
- 配置项目信息
- 选择依赖
- 点击 Finish
Eclipse/STS
- 点击 File -> New -> Spring Starter Project
- 配置项目信息
- 选择依赖
- 点击 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 配置文件优先级
- 命令行参数
- java:comp/env里的JNDI属性
- JVM系统属性
- 操作系统环境变量
- RandomValuePropertySource配置的random.*属性值
- jar包外部的application-{profile}.properties或application.yml(带spring.profile)配置文件
- jar包内部的application-{profile}.properties或application.yml(带spring.profile)配置文件
- jar包外部的application.properties或application.yml(不带spring.profile)配置文件
- 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
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 tomcat: max-threads: 200 min-spare-threads: 10 max-connections: 10000 connection-timeout: 5000
|
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: maximum-pool-size: 20 minimum-idle: 5 idle-timeout: 30000 connection-timeout: 30000 max-lifetime: 1800000
|
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 show-sql: true properties: hibernate: format_sql: true use_sql_comments: true open-in-view: false
|
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 lettuce: pool: max-active: 8 max-idle: 8 min-idle: 0 max-wait: -1
|
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 org.hibernate: ERROR 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 启动流程
创建SpringApplication对象
- 推断应用类型(SERVLET、REACTIVE、NONE)
- 查找并加载所有可用的初始化器
- 查找所有的应用程序监听器
- 推断并设置main方法的定义类
运行SpringApplication
- 启动计时器
- 发布应用启动事件
- 准备环境
- 创建上下文对象
- 预处理上下文
- 刷新上下文
- 后置处理上下文
- 发布应用已启动事件
- 执行runners
6.2 自动配置原理
SpringBoot自动配置是通过@EnableAutoConfiguration
注解实现的,其核心步骤如下:
- @SpringBootApplication:包含了@EnableAutoConfiguration
- @EnableAutoConfiguration:导入AutoConfigurationImportSelector
- 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); application.setBannerMode(Banner.Mode.OFF); 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
| mvn spring-boot:run
mvn spring-boot:run -Dspring.profiles.active=prod
mvn spring-boot:run -Dspring-boot.run.jvmArguments="-Xms512m -Xmx1024m"
|
使用Gradle
1 2 3 4 5
| gradle bootRun
gradle bootRun --args='--spring.profiles.active=prod'
|
使用打包后的JAR
1 2 3 4 5 6 7 8 9 10 11
| mvn clean package
java -jar target/myapp-0.0.1-SNAPSHOT.jar
java -jar target/myapp-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod
java -Xms512m -Xmx1024m -jar target/myapp-0.0.1-SNAPSHOT.jar
|
9.3 使用Spring Boot CLI
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 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"); when(myRepository.findById(1L)).thenReturn(Optional.of(entity)); MyDto result = myService.getById(1L); assertNotNull(result); assertEquals(1L, result.getId()); assertEquals("Test", result.getName()); verify(myRepository).findById(1L); } }
|
12. 总结
SpringBoot通过约定大于配置的理念,大大简化了Spring应用的开发。本文详细介绍了SpringBoot的配置和启动方式,包括:
- SpringBoot的核心特性和优势
- 项目结构和创建方式
- 核心配置文件和常用配置项
- 启动原理和自动配置机制
- 启动类详解和启动方式
- 常用注解和最佳实践
通过掌握这些知识,开发者可以更高效地使用SpringBoot开发企业级应用。
参考资料
- Spring Boot官方文档
- Spring Boot GitHub仓库
- Spring Initializr
- Spring Boot Actuator文档
- Spring Boot Admin