01 概要
Spring Boot 是 Java 领域最流行的 快速开发框架,专为简化 Spring 应用的初始搭建和开发而设计。
一、Spring Boot 解决了什么问题?
- 传统 Spring 痛点
• 繁琐的 XML 配置
• 需要手动管理依赖版本
• 部署依赖外部 Web 服务器(如 Tomcat) - Spring Boot 的答案
• 约定优于配置:自动配置 80% 的默认设置
• 内嵌服务器:直接打包成可执行 JAR
• 起步依赖:一键集成常用技术栈(如数据库、安全模块)
二、核心特性
1. 自动配置(Auto-Configuration)
@SpringBootApplication // 核心注解:开启自动配置
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args); // 启动应用
}
}
• 自动探测:根据类路径中的 Jar 包自动配置 Bean(如发现 spring-boot-starter-data-jpa
则自动配置数据源)
2. 起步依赖(Starters)
<!-- pom.xml 示例 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <!-- Web开发全家桶 -->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId> <!-- 测试模块 -->
</dependency>
三、快速入门
1. 创建项目
• 访问 start.spring.io(Spring Initializr)
• 选择依赖:Spring Web
2. 编写 Controller
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello(@RequestParam(required = false) String name) {
return "Hello, " + (name != null ? name : "World");
}
}
3. 运行与测试
mvn spring-boot:run # 启动应用
访问 http://localhost:8080/hello?name=Spring
查看结果
四、常用技术整合
技术栈 | 用途 | 起步依赖名称 | 关键配置示例 | 代码注解/示例 |
---|---|---|---|---|
Web 开发 | 快速构建 REST API | spring-boot-starter-web |
server.port=8080 |
@RestController , @GetMapping("/api") |
JPA + MySQL | 关系型数据库操作 | spring-boot-starter-data-jpa |
spring.datasource.url=jdbc:mysql://localhost:3306/db spring.jpa.hibernate.ddl-auto=update |
@Entity , @Repository , JpaRepository<User, Long> |
MyBatis | SQL 映射框架 | mybatis-spring-boot-starter |
mybatis.mapper-locations=classpath:mapper/*.xml |
@Mapper , @Select("SELECT * FROM user") |
Redis | 缓存/分布式锁 | spring-boot-starter-data-redis |
spring.redis.host=localhost spring.redis.port=6379 |
@Autowired private RedisTemplate<String, Object> redisTemplate; |
Security | 认证与授权 | spring-boot-starter-security |
spring.security.user.name=admin spring.security.user.password=123456 |
@EnableWebSecurity , configure(HttpSecurity http) |
Swagger | API 文档生成 | springdoc-openapi-starter-webmvc-ui |
springdoc.api-docs.path=/api-docs springdoc.swagger-ui.path=/swagger |
@Operation(summary="Get user") , @OpenAPIDefinition |
Scheduling | 定时任务 | spring-boot-starter (内置) |
@EnableScheduling |
@Scheduled(cron="0 0 8 * * ?") |
阿里云 OSS | 文件存储 | 无官方 starter,需手动引入 SDK | aliyun.oss.endpoint=oss-cn-beijing.aliyuncs.com aliyun.oss.accessKeyId=xxx |
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); |
WebSocket | 实时通信 | spring-boot-starter-websocket |
无特殊配置 | @MessageMapping("/chat") , SimpMessagingTemplate.convertAndSend(...) |
使用场景说明
数据库整合
• JPA:适合快速 CRUD 开发,自动生成 SQL。
• MyBatis:需要复杂 SQL 或已有 SQL 优化的场景。缓存与消息队列
• Redis:高频读取数据的缓存,或分布式锁实现。安全与监控
• Security:快速实现登录验证和权限控制。前端与文档
• Swagger:自动生成 API 文档,方便前后端联调。
配置与代码示例
1. JPA + MySQL 配置
# application.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: 123456
jpa:
hibernate:
ddl-auto: update
show-sql: true
2. Redis 缓存使用
@Service
public class UserService {
@Autowired
private RedisTemplate<String, User> redisTemplate;
public User getUserById(String id) {
User user = redisTemplate.opsForValue().get("user:" + id);
if (user == null) {
user = userRepository.findById(id); // 从数据库查询
redisTemplate.opsForValue().set("user:" + id, user, 30, TimeUnit.MINUTES);
}
return user;
}
}
3. Swagger 配置
@Configuration
@OpenAPIDefinition(info = @Info(title = "API 文档", version = "1.0"))
public class SwaggerConfig {
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.info(new Info().title("电商系统 API").version("1.0"));
}
}
五、开发效率工具
配置文件多环境支持
# application-dev.yml(开发环境)
server:
port: 8080
---
# application-prod.yml(生产环境)
server:
port: 80
启动命令:java -jar myapp.jar --spring.profiles.active=prod
八、常见问题解决方案
端口冲突
server.port=8081 # 修改端口
跨域问题
@Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("GET", "POST"); } }
静态资源访问
将文件放在src/main/resources/static
目录下
通过 Spring Boot,开发者可以专注于业务逻辑而非配置,真正实现 快速交付生产级应用。建议从官方文档开始实践:Spring Boot Official Docs
Spring Boot中文网
02 Spring Boot自动配置原理
1. 入口:@SpringBootApplication
注解
Spring Boot应用的启动类通常标注了@SpringBootApplication
,该注解是一个组合注解,包含:
• @EnableAutoConfiguration
:触发自动装配的核心注解。
• @ComponentScan
:扫描当前包及子包的组件(如@Component
、@Service
等)。
• @SpringBootConfiguration
:标记为Spring Boot配置类。
@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
2. @EnableAutoConfiguration
的作用
@EnableAutoConfiguration
通过 @Import
导入 AutoConfigurationImportSelector
类,该类的核心任务是:
• 扫描所有 META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
文件
• 加载其中定义的自动配置类(如 Spring MVC
、DataSource
等配置类)。
3. 自动配置类的加载机制
自动配置类以 XXXAutoConfiguration
命名,例如:
• ServletWebServerFactoryAutoConfiguration
(内嵌Web服务器配置)
• DataSourceAutoConfiguration
(数据源配置)
这些类通过 条件注解(Conditional Annotations) 控制是否生效,例如:
• @ConditionalOnClass
:类路径存在指定类时生效。
@ConditionalOnClass({Servlet.class, DispatcherServlet.class})
public class WebMvcAutoConfiguration { /* ... */ }
• @ConditionalOnProperty
:特定配置属性存在时生效。
• @ConditionalOnMissingBean
:当容器中不存在指定Bean时生效(允许用户自定义Bean覆盖默认配置)。
4. Starter 依赖与自动配置的关系
• Starter(如 spring-boot-starter-web
)提供一组预置依赖(如Tomcat、Spring MVC)和对应的自动配置类。
• 约定优于配置:只要引入Starter,Spring Boot自动装配相关组件(例如引入spring-boot-starter-data-jpa
会自动配置数据源和JPA相关Bean)。
5. 自动装配的完整流程
- 启动应用:执行
SpringApplication.run()
。 - 加载
@EnableAutoConfiguration
:触发AutoConfigurationImportSelector
。 - 扫描所有
AutoConfiguration.imports
文件:获取所有自动配置类。 - 过滤条件注解:仅保留满足条件的配置类(如类路径存在、属性已配置等)。
- 按优先级排序:通过
@AutoConfigureOrder
或@Order
控制加载顺序。 - 注册Bean:将生效的配置类中的Bean定义加载到IoC容器。
6. 覆盖默认自动配置
用户可通过以下方式自定义配置:
• 定义同名Bean:使用@Bean
覆盖自动配置的Bean(@ConditionalOnMissingBean
会生效)。
• 调整配置属性:通过application.properties
或application.yml
覆盖默认属性。
• 排除特定自动配置类:
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
7. 示例:DataSource自动配置
以数据源为例:
- 引入
spring-boot-starter-jdbc
:类路径下存在DataSource
和HikariCP
。 - 触发
DataSourceAutoConfiguration
:检查到DataSource
类存在。 - 读取
spring.datasource.*
配置:自动创建DataSource
Bean。 - 用户自定义:若手动定义
@Bean DataSource
,则默认配置失效。
总结
Spring Boot自动装配通过条件化加载配置类和Starter依赖管理,实现了“开箱即用”的体验。其核心是:
• 条件注解:按需加载配置。
• Starter机制:依赖与配置的捆绑。
• 约定优于配置:减少手动配置,提升开发效率。
03 yaml语法
YAML(YAML Ain’t Markup Language)是一种简洁的数据序列化语言,广泛用于配置文件(如Spring Boot的application.yml
)。其语法强调可读性,通过缩进和符号表示结构。
1. 基本语法
• 键值对:用冒号:
分隔键和值,冒号后必须加空格。
name: "John Doe"
age: 30
• 注释:以#
开头。
# 这是注释
key: value
• 字符串:可省略引号,特殊字符(如:
)需加双引号。
message: Hello, World!
path: "C:\\Windows" # 转义特殊字符
2. 数据类型
标量类型(Scalars)
• 字符串、布尔值、数字、null:
string: "Hello"
boolean: true
number: 123
null-value: null
• 多行字符串:
description: |
This is a multi-line
string with line breaks.
single-line: >
This is a single-line
string without line breaks.
集合类型
• 列表(List):用短横线-
表示数组项。
fruits:
- Apple
- Banana
- Orange
• 对象(Map):通过缩进表示嵌套结构。
user:
name: "Alice"
address:
city: "New York"
zip: 10001
3. 高级语法
数据类型自动转换
• YAML会自动推断类型,也可强制指定:
number-as-string: !!str 123 # 强制转为字符串
4. 缩进与层级
• 缩进必须用空格(不能使用Tab),同一层级缩进对齐。
server:
port: 8080
ssl:
enabled: true
key-store: "keystore.p12"
5. 常见应用示例
Spring Boot配置
server:
port: 8080
servlet:
context-path: /api
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: "123456"
logging:
level:
org.springframework: INFO
• 文件扩展名:.yml
或 .yaml
(两者等价)。
6. 核心区别
特性 | YAML(.yml) | Properties |
---|---|---|
数据结构 | 支持嵌套层级(通过缩进或符号)。 | 扁平结构,通过. 模拟层级。 |
语法 | 缩进敏感(必须用空格),冒号: 分隔键值。 |
等号= 或冒号: 分隔键值,无缩进。 |
可读性 | 高(层次清晰,适合复杂配置)。 | 较低(长键名易冗余)。 |
数据类型支持 | 自动推断类型(字符串、布尔、数字、列表、对象)。 | 所有值均为字符串,需手动转换类型。 |
高级功能 | 支持锚点(& )、引用(* )、多行文本等。 |
仅支持键值对和简单注释。 |
注释 | 使用 # 。 |
使用 # 或 ! 。 |
重复键处理 | 不允许重复键(覆盖或报错)。 | 允许重复键(最后一个生效)。 |
7. 语法对比示例
YAML 示例
# 支持嵌套对象和列表
server:
port: 8080
ssl:
enabled: true
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
Properties 示例
# 扁平化结构,用`.`表示层级
server.port=8080
server.ssl.enabled=true
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
8. 优缺点对比
YAML 的优势
• 结构化配置:适合表达复杂嵌套关系(如 Kubernetes 的 Deployment 配置)。
• 更少的冗余:避免长键名重复(如 server.ssl.enabled
vs 缩进层级)。
• 多行文本支持:方便编写长文本或脚本(如 Shell 命令)。
Properties 的优势
• 简单直接:适合快速定义少量配置。
• 兼容性广:几乎所有框架和语言都支持。
• 无缩进陷阱:避免因缩进错误导致解析失败。
9. YAML 与 Properties 的互操作性
在 Spring Boot 中,二者可以共存,但优先级不同:
• .properties
优先级高于 .yml
。
• 若同时存在 application.yml
和 application.properties
,后者会覆盖前者的同名配置。
10. 注意事项
- 缩进必须一致(如2或4空格),否则解析失败。
- 避免重复键名,后定义的键会覆盖前者。
- 特殊字符需转义(如
:
、{
、}
需加引号)。
04 YAML为实体类赋值
1. 使用 @Value
注解注入单个属性
适用场景:直接注入YAML中的简单值(如字符串、数字、布尔值)。
步骤:
- 在YAML中定义属性。
- 在实体类字段上使用
@Value("${property.path}")
注解。
示例:
# application.yml
app:
name: "MyApp"
version: 1.0.0
@Component
public class AppConfig {
@Value("${app.name}")
private String name;
@Value("${app.version}")
private String version;
// Getters & Setters
}
注意事项:
• 适用于少量简单属性。
• 不支持类型校验和嵌套对象绑定。
2. 使用 @ConfigurationProperties
绑定组属性
适用场景:将一组相关属性绑定到实体类(支持嵌套对象、列表、类型校验)。
步骤:
- 在YAML中定义层级化属性。
- 创建实体类,添加
@ConfigurationProperties(prefix="前缀")
注解。 - 通过Setter方法或构造器注入值。
示例:
# application.yml
user:
name: "Alice"
age: 25
address:
city: "Shanghai"
zip: 200000
hobbies:
- Reading
- Coding
@Component
@ConfigurationProperties(prefix = "user")
public class UserProfile {
private String name;
private int age;
private Address address;
private List<String> hobbies;
// 嵌套对象需定义内部类
public static class Address {
private String city;
private int zip;
// Getters & Setters
}
// Getters & Setters(必须提供)
}
启用配置类:
在启动类或配置类上添加@EnableConfigurationProperties
:
@SpringBootApplication
@EnableConfigurationProperties(UserProfile.class)
public class MyApp { ... }
优点:
• 支持复杂结构(嵌套对象、集合)。
• 自动类型转换(如字符串转数字、列表)。
• 结合@Validated
实现数据校验(如@NotNull
)。
05 JSR 303
JSR 303(Bean Validation 1.0)和其后续版本JSR 380(Bean Validation 2.0)是Java平台中用于声明式数据验证的标准规范,通过注解简化数据校验逻辑,确保对象属性符合业务规则。
1. 核心特性
• 声明式验证:通过注解(如@NotNull
, @Size
)标记字段约束,无需手动编写校验逻辑。
• 标准化:统一不同框架(如Spring、Hibernate)的校验方式。
• 支持嵌套校验:可验证对象内部的其他对象(如User
中的Address
)。
2. 常用注解
以下是Bean Validation的核心注解(以JSR 380为例):
注解 | 作用 | 示例 |
---|---|---|
@NotNull |
值不能为null |
@NotNull private String name; |
@Size(min, max) |
字符串/集合长度在范围内 | @Size(min=2, max=10) String password; |
@Min(value) / @Max |
数字最小值/最大值 | @Min(18) int age; |
@Email |
校验邮箱格式 | @Email private String email; |
@Pattern(regexp) |
正则表达式匹配 | @Pattern(regexp = "^\\d{3}-\\d{2}$") |
@Positive / @Negative |
数值必须为正/负 | @Positive double price; |
@Future / @Past |
日期必须在未来/过去 | @Future LocalDate eventDate; |
@NotEmpty |
字符串/集合不能为空(非null 且非空) |
@NotEmpty List<String> roles; |
@Valid |
触发嵌套对象的校验 | @Valid private Address address; |
3. 使用示例
场景:校验用户注册信息
public class User {
@NotBlank(message = "用户名不能为空")
private String username;
@Size(min = 6, max = 20, message = "密码长度需在6-20位之间")
private String password;
@Email(message = "邮箱格式错误")
private String email;
@Valid // 嵌套校验Address对象
private Address address;
}
public class Address {
@NotBlank(message = "城市不能为空")
private String city;
}
触发校验(Spring Boot中):
@RestController
public class UserController {
@PostMapping("/register")
public ResponseEntity<?> registerUser(@Valid @RequestBody User user, BindingResult result) {
if (result.hasErrors()) {
// 返回校验错误信息
return ResponseEntity.badRequest().body(result.getAllErrors());
}
// 执行业务逻辑
return ResponseEntity.ok("注册成功");
}
}
4. 集成Spring Boot
Spring Boot默认集成了Hibernate Validator(Bean Validation的实现),无需额外配置:
添加依赖(已包含在
spring-boot-starter-web
中):<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
在Controller中使用
@Valid
:触发校验。处理校验错误:通过
BindingResult
捕获错误信息。
5. 自定义校验注解
若标准注解不满足需求,可自定义校验逻辑。
示例:校验字符串是否为手机号
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = PhoneNumberValidator.class)
public @interface PhoneNumber {
String message() default "手机号格式错误";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class PhoneNumberValidator implements ConstraintValidator<PhoneNumber, String> {
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
return value != null && value.matches("^1[3-9]\\d{9}$");
}
}
使用自定义注解:
public class User {
@PhoneNumber
private String phone;
}
06 介绍多环境配置和配置文件位置
1. 多环境配置的实现
1.1 配置文件命名规则
Spring Boot通过application-{profile}.yml
(或.properties
)支持多环境配置,例如:
• application-dev.yml
:开发环境。
• application-test.yml
:测试环境。
• application-prod.yml
:生产环境。
1.2 激活指定环境
在**主配置文件(application.yml
)**中指定激活的环境:
# application.yml
spring:
profiles:
active: dev # 激活开发环境
或通过启动命令动态指定:
java -jar myapp.jar --spring.profiles.active=prod
1.3 环境专属配置
每个环境配置文件仅包含该环境特有的属性,例如:
# application-prod.yml
server:
port: 8080
ssl:
enabled: true
spring:
datasource:
url: jdbc:mysql://prod-db:3306/mydb
username: prod_user
1.4 配置继承与覆盖
• 通用配置:写在application.yml
中,所有环境共享。
• 环境专属配置:写在application-{profile}.yml
中,优先级高于通用配置。
2. 配置文件的存储位置
Spring Boot按以下顺序加载配置文件(优先级从高到低):
2.1 外部化配置路径
file:./config/
:项目根目录下的config
文件夹。myapp/ ├── config/ │ └── application.yml └── application.jar
file:./
:项目根目录。classpath:/config/
:类路径下的config
目录。classpath:/
:类路径根目录。
类路径–> resource包下和java包下
2.2 配置加载规则
• 外部配置文件优先级高于Jar内部:例如,file:./config/application.yml
会覆盖Jar内的application.yml
。
• 多环境配置同样遵循位置优先级:例如,file:./config/application-prod.yml
优先于classpath:/application-prod.yml
。
3. 多环境配置示例
3.1 项目结构
src/main/resources/
├── application.yml # 通用配置
├── application-dev.yml # 开发环境
└── application-prod.yml # 生产环境
3.2 通用配置(application.yml
)
# 通用属性(所有环境共享)
app:
name: "MyApp"
version: 1.0.0
# 默认激活开发环境
spring:
profiles:
active: dev
3.3 开发环境配置(application-dev.yml
)
server:
port: 8081
spring:
datasource:
url: jdbc:mysql://localhost:3306/dev_db
username: dev_user
password: dev_pass
3.4 生产环境配置(application-prod.yml
)
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://prod-db:3306/prod_db
username: prod_user
password: prod_pass
4. 动态切换环境的方式
4.1 命令行参数
java -jar myapp.jar --spring.profiles.active=test
4.2 环境变量
export SPRING_PROFILES_ACTIVE=prod
java -jar myapp.jar
4.3 IDE配置
在运行配置的VM options
或Program arguments
中添加:
-Dspring.profiles.active=prod
5. 配置优先级总结
配置来源 | 优先级(高 → 低) |
---|---|
命令行参数(--key=value ) |
最高 |
外部配置文件(file:./config/ ) |
↑ |
Jar内部配置文件(classpath:/ ) |
↓ |
默认配置(application.yml ) |
最低 |
07 静态资源导入
Spring Boot 的静态资源处理是其Web开发中的重要特性,它简化了前端资源(如HTML、CSS、JS、图片等)的管理和访问。
1. 默认静态资源路径
Spring Boot 默认会在以下类路径(classpath
)目录中查找静态资源,优先级从高到低如下:
classpath:/META-INF/resources/
(例如:JAR包内META-INF/resources
目录)classpath:/resources/
(对应项目中的src/main/resources/resources/
)classpath:/static/
(最常用,对应src/main/resources/static/
)classpath:/public/
(对应src/main/resources/public/
)
验证默认路径
• 创建文件:在src/main/resources/static/js/app.js
中添加一个JS文件。
• 访问URL:http://localhost:8080/js/app.js
,若返回文件内容,则配置生效。
2. 自定义静态资源路径
若需添加或覆盖默认路径,可通过以下方式配置:
2.1 通过配置文件
在application.yml
中设置:
spring:
resources:
static-locations:
- classpath:/custom-static/
- file:/opt/static/
• classpath:/custom-static/
:类路径下的自定义目录。
• file:/opt/static/
:文件系统的绝对路径。
• 注意:配置后会覆盖所有默认路径,若需保留默认路径,需显式包含:
static-locations:
- classpath:/META-INF/resources/
- classpath:/resources/
- classpath:/static/
- classpath:/public/
- classpath:/custom-static/
2.2 通过Java配置类
实现WebMvcConfigurer
接口,重写addResourceHandlers
方法:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/**") // 匹配所有URL路径
.addResourceLocations("classpath:/custom-static/", "file:/opt/static/")
.setCachePeriod(3600); // 缓存时间(秒)
}
}
3. 静态资源访问规则
3.1 URL路径映射
• 默认规则:静态资源文件可通过URL直接访问,路径与资源目录结构一致。
例如:static/css/style.css
➔ http://localhost:8080/css/style.css
• 自定义路径前缀:
若需为静态资源添加统一前缀(如/assets/**
):
spring:
mvc:
static-path-pattern: /assets/**
• 访问URL变为:http://localhost:8080/assets/css/style.css
3.2 缓存控制
• 开发环境禁用缓存:
spring:
resources:
cache:
period: 0 # 缓存时间(秒),0表示禁用
• 生产环境启用缓存:
spring:
resources:
cache:
period: 86400 # 缓存24小时
4. 常见问题与解决方案
4.1 静态资源404错误
• 可能原因:
• 文件未放在默认或自定义的静态资源目录中。
• 路径拼写错误(区分大小写)。
• 自定义配置覆盖了默认路径但未正确包含原有路径。
• 排查步骤:
- 检查文件是否在
target/classes/static/
(编译后目录)中存在。 - 查看Spring Boot启动日志,确认加载的资源路径:
... Mapped URL path [/**] onto locations [classpath:/custom-static/]
08 templates
在Spring Boot中,templates
目录是用于存放动态模板文件的核心位置,结合模板引擎(如Thymeleaf、FreeMarker等)实现动态页面渲染。
1. templates目录的作用
• 动态页面生成:模板文件(.html
、.ftl
等)可嵌入动态数据(如变量、循环、条件语句),生成最终的HTML页面。
• 与静态资源的区别:
• 静态资源(static/
目录):直接返回给浏览器的固定文件(如.html
、.css
)。
• 模板文件(templates/
目录):需模板引擎渲染后返回动态内容。
2. 默认位置与配置
2.1 目录路径
• 默认路径:src/main/resources/templates/
Spring Boot自动扫描该目录下的模板文件。
2.2 模板引擎集成
Spring Boot支持多种模板引擎,需添加对应依赖:
模板引擎 | 依赖配置(Maven) | 模板后缀 |
---|---|---|
Thymeleaf | spring-boot-starter-thymeleaf |
.html |
FreeMarker | spring-boot-starter-freemarker |
.ftl |
Mustache | spring-boot-starter-mustache |
.mustache |
示例:集成Thymeleaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
3. 模板引擎使用示例
3.1 Thymeleaf模板
创建模板文件:
src/main/resources/templates/home.html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Home Page</title> </head> <body> <h1 th:text="${message}">Default Message</h1> <ul> <li th:each="item : ${items}" th:text="${item}"></li> </ul> </body> </html>
Controller返回视图:
@Controller public class HomeController { @GetMapping("/home") public String home(Model model) { model.addAttribute("message", "Welcome to Thymeleaf!"); model.addAttribute("items", Arrays.asList("Item 1", "Item 2", "Item 3")); return "home"; // 对应templates/home.html } }
访问URL:
http://localhost:8080/home
,渲染动态内容。
3.2 FreeMarker模板
模板文件:
src/main/resources/templates/home.ftl
<!DOCTYPE html> <html> <head> <title>FreeMarker Example</title> </head> <body> <h1>${message}</h1> <ul> <#list items as item> <li>${item}</li> </#list> </ul> </body> </html>
Controller逻辑与Thymeleaf相同,仅需修改模板文件名后缀。
4. 模板引擎配置
在application.yml
中自定义模板引擎行为:
4.1 Thymeleaf配置
spring:
thymeleaf:
prefix: classpath:/templates/ # 模板文件路径(默认)
suffix: .html # 模板后缀(默认)
cache: false # 开发时禁用缓存(实时生效)
mode: HTML # 模板模式(HTML、LEGACYHTML5等)
4.2 FreeMarker配置
spring:
freemarker:
template-loader-path: classpath:/templates/ # 模板路径
suffix: .ftl # 模板后缀
cache: false # 开发禁用缓存
settings:
datetime_format: yyyy-MM-dd HH:mm:ss # 日期格式
5. 最佳实践
5.1 模板目录结构
按功能或模块组织模板文件:
templates/
├── common/ # 公共模板片段(如页眉、页脚)
├── user/ # 用户相关页面
├── admin/ # 管理后台页面
└── error/ # 自定义错误页面(如404.html)
5.2 公共片段复用
使用模板引擎的**片段(Fragment)**功能,避免重复代码:
<!-- Thymeleaf示例:common/header.html -->
<header th:fragment="header">
<nav>...</nav>
</header>
<!-- 引入片段 -->
<div th:replace="~{common/header :: header}"></div>
6. 常见问题
Q1:模板文件修改后不生效?
• 原因:模板引擎缓存未关闭(生产模式默认启用缓存)。
• 解决:配置spring.thymeleaf.cache=false
(开发环境)。
Q2:访问模板页面返回404?
• 检查项:
- 模板文件是否在
templates/
目录下。 - Controller方法是否使用
@Controller
(非@RestController
)。 - 视图名称是否与模板文件名一致(区分大小写)。
Q3:如何返回JSON而非视图?
• 方法:使用@RestController
或方法添加@ResponseBody
,直接返回数据对象而非视图名称。
7. 总结
• 核心作用:templates
目录存放动态模板文件,结合模板引擎实现服务端渲染。
• 常用引擎:Thymeleaf(推荐)、FreeMarker、Mustache。
• 关键配置:模板路径、缓存开关、自定义格式化。
• 最佳实践:模块化组织模板、复用片段、确保安全。
09 首页和图标定制
一、首页定制
1. 默认首页规则
Spring Boot默认在以下位置查找 index.html
作为首页:
• 静态资源目录:
classpath:/static/
、classpath:/public/
、classpath:/resources/
、classpath:/META-INF/resources/
• 模板引擎目录:
如果集成了模板引擎(如Thymeleaf、FreeMarker),优先使用 classpath:/templates/index.html
。
2. 创建默认首页
• 静态首页(无动态内容):
在 src/main/resources/static/
下创建 index.html
:
<!DOCTYPE html>
<html>
<head>
<title>My Home Page</title>
</head>
<body>
<h1>Welcome to My App!</h1>
</body>
</html>
• 动态首页(结合模板引擎):
例如使用Thymeleaf,将 index.html
放在 src/main/resources/templates/
下,并通过Controller返回视图:
@Controller
public class HomeController {
@GetMapping("/")
public String home() {
return "index"; // 返回templates/index.html
}
}
3. 自定义首页路径
• 修改默认路径:
在 application.yml
中指定自定义首页:
spring:
mvc:
welcome-page: /custom-home.html # 需放在静态资源目录下
4. 常见问题
• 首页不生效:
• 检查文件是否在正确的静态资源目录中。
• 清除浏览器缓存或使用无痕模式访问。
• 确认没有其他Controller拦截了根路径("/"
)。
二、图标(Favicon)定制
1. 默认图标规则
Spring Boot默认在静态资源根目录查找 favicon.ico
:
• 路径:
classpath:/static/
、classpath:/public/
、classpath:/resources/
、classpath:/META-INF/resources/
2. 添加自定义图标
• 步骤:
- 将
favicon.ico
文件放入src/main/resources/static/
。 - 重启应用,浏览器访问
http://localhost:8080/favicon.ico
验证。
3. 高级配置
• 自定义图标路径:
若需使用非默认路径或文件名:
spring:
mvc:
favicon:
enabled: true
path: /icons/my-icon.ico # 相对静态资源目录的路径
• 禁用默认图标:
spring:
mvc:
favicon:
enabled: false
4. 常见问题
• 图标不显示:
• 浏览器缓存:清除浏览器缓存缓存。
• 文件格式:确保为 .ico
格式(可用PNG转ICO工具生成)。
三、结合模板引擎的首页增强
以Thymeleaf为例,动态渲染首页数据:
1. 动态数据绑定
@Controller
public class HomeController {
@GetMapping("/")
public String home(Model model) {
model.addAttribute("message", "Welcome, User!");
return "index";
}
}
2. 模板文件(templates/index.html
)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Home Page</title>
<link rel="icon" th:href="@{/favicon.ico}" type="image/x-icon"/>
</head>
<body>
<h1 th:text="${message}">Default Welcome Message</h1>
</body>
</html>
四、最佳实践
- 图标格式:使用在线工具生成多尺寸ICO文件,确保兼容性。
• 推荐工具:AILogoEasy - 首页优化:
• 对于单页应用(SPA),结合前端框架(如Vue/React)托管首页。
• 对于传统应用,使用模板引擎动态加载数据。 - 缓存策略:
• 为静态资源添加版本号(如favicon.ico?v=1.0.0
)避免缓存问题。
总结
通过合理配置静态资源和模板引擎,可轻松定制Spring Boot应用的首页和图标。关键步骤包括:
• 首页:将 index.html
放在静态目录或模板目录中。
• 图标:提供 favicon.ico
并确保路径正确。
• 动态内容:结合Controller和模板引擎增强交互性。
10 MVC配置
1. 核心组件与流程
Spring MVC 基于 DispatcherServlet 作为前端控制器,协调请求处理流程:
- 请求分发:DispatcherServlet 接收所有HTTP请求。
- 处理器映射:通过
HandlerMapping
找到匹配的控制器方法。 - 处理器适配:
HandlerAdapter
调用控制器方法并处理参数绑定。 - 视图解析:
ViewResolver
将逻辑视图名解析为具体视图(如HTML、JSON)。 - 视图渲染:视图模板引擎(如Thymeleaf)生成响应内容。
2. Spring Boot 的自动配置
Spring Boot 通过 WebMvcAutoConfiguration
类提供默认MVC配置,包括:
• 静态资源处理:映射 /static
、/public
等目录。
• 默认视图解析器:如 InternalResourceViewResolver
。
• 消息转换器:自动注册 JSON、XML 转换器(如 MappingJackson2HttpMessageConverter
)。
• 格式化器:日期、数字等类型转换。
生效条件:项目中无自定义 WebMvcConfigurationSupport
或 @EnableWebMvc
注解。
3. 自定义 MVC 配置的三种方式
3.1 实现 WebMvcConfigurer
接口
作用:扩展默认配置(推荐方式)。
示例:添加拦截器、自定义视图解析器。
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
// 添加拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/admin/**");
}
// 自定义视图控制器
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
}
}
3.2 使用 @EnableWebMvc
注解
作用:完全接管MVC配置,禁用Spring Boot的自动配置。
适用场景:需要完全自定义MVC行为(慎用,通常不建议)。
@Configuration
@EnableWebMvc // 禁用自动配置
public class FullMvcConfig implements WebMvcConfigurer {
// 需手动配置所有MVC组件
}
3.3 自定义 WebMvcConfigurationSupport
子类
作用:与 @EnableWebMvc
等效,通过继承配置核心组件。
示例:自定义资源处理器。
@Configuration
public class CustomMvcConfig extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/custom/**")
.addResourceLocations("classpath:/custom-static/");
}
}
4. 关键配置项详解
4.1 静态资源映射
• 默认路径:classpath:/static/
, classpath:/public/
等。
• 自定义路径:
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/assets/**")
.addResourceLocations("classpath:/my-assets/");
}
4.2 拦截器(Interceptor)
• 创建拦截器:
public class AuthInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) {
// 验证登录状态
return true; // 放行请求
}
}
• 注册拦截器:
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new AuthInterceptor())
.excludePathPatterns("/login", "/static/**");
}
4.3 跨域配置(CORS)
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("https://example.com")
.allowedMethods("GET", "POST");
}
4.4 消息转换器
替换或添加自定义转换器(如处理 Protobuf):
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new ProtobufHttpMessageConverter());
}
5. 配置优先级与覆盖规则
• 优先级顺序:
@EnableWebMvc
或 WebMvcConfigurationSupport
> 自定义 WebMvcConfigurer
> 自动配置。
• 叠加生效:多个 WebMvcConfigurer
实现的配置会合并,而非覆盖。
6. 常见问题与解决
Q1:自定义配置未生效?
• 检查类是否被 @Configuration
注解。
• 确认未误加 @EnableWebMvc
(除非需完全自定义)。
Q2:静态资源访问404?
• 确认资源路径是否在配置的 static-locations
中。
• 检查是否被拦截器拦截(如未排除 /static/**
)。
Q3:日期格式化不生效?
• 全局配置:
@Override
public void addFormatters(FormatterRegistry registry) {
DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
registrar.setUseIsoFormat(true);
registrar.registerFormatters(registry);
}
7. 总结
Spring MVC 的配置原理围绕 扩展性 与 约定优于配置 展开:
• 自动配置:快速启动,满足大部分场景。
• 自定义扩展:通过 WebMvcConfigurer
按需调整。
• 完全控制:使用 @EnableWebMvc
或 WebMvcConfigurationSupport
深度定制。
掌握这些机制,可以灵活应对不同业务需求,同时保持代码简洁高效。
11 bootstrap模板
Bootstrap 模板详解
Bootstrap 是一个流行的开源前端框架,用于快速构建 响应式、移动优先 的网页和 Web 应用。以下是 Bootstrap 模板的核心组成、使用方法和整合到 Spring Boot 项目的实践指南。
一、Bootstrap 模板基础
1. 核心特性
• 响应式布局:自动适配手机、平板、PC 等不同屏幕尺寸。
• 预定义组件:导航栏、按钮、表单、卡片等常用 UI 元素。
• 工具类:间距、排版、颜色等 CSS 工具类快速定制样式。
• 插件支持:模态框、轮播图等交互组件(依赖 jQuery 或 Popper.js)。
二、Bootstrap 模板结构
一个标准的 Bootstrap 模板包含以下部分:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<!-- 1. 元数据 -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bootstrap 模板</title>
<!-- 2. Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<!-- 3. 页面内容 -->
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">Logo</a>
<!-- 导航项 -->
</div>
</nav>
<div class="container mt-4">
<h1 class="text-primary">欢迎使用 Bootstrap</h1>
<button class="btn btn-success">点击按钮</button>
</div>
<!-- 4. Bootstrap JS 及依赖 -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
三、整合到 Spring Boot 项目
1. 引入 Bootstrap 资源
• 方式一:CDN 引入(推荐开发使用)
直接在 Thymeleaf 模板中引用 CDN 链接:
<link th:href="@{https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css}" rel="stylesheet">
<script th:src="@{https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js}"></script>
• 方式二:本地静态资源
将 Bootstrap 文件下载到 src/main/resources/static/
目录:
src/main/resources/static/
├── css/
│ └── bootstrap.min.css
└── js/
└── bootstrap.bundle.min.js
模板中引用本地路径:
<link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
<script th:src="@{/js/bootstrap.bundle.min.js}"></script>
2. 结合 Thymeleaf 的动态模板
在 src/main/resources/templates/
下创建页面(如 index.html
):
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Spring Boot + Bootstrap</title>
<link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container">
<a class="navbar-brand" th:href="@{/}">首页</a>
<div class="navbar-nav">
<a class="nav-link" th:href="@{/users}">用户管理</a>
</div>
</div>
</nav>
<div class="container mt-4">
<h1 th:text="${message}">默认标题</h1>
<div class="alert alert-success" th:if="${success}">操作成功!</div>
</div>
<script th:src="@{/js/bootstrap.bundle.min.js}"></script>
</body>
</html>
四、Bootstrap 核心功能实践
1. 响应式网格系统
使用 .row
和 .col-*
类实现自适应布局:
<div class="container">
<div class="row">
<div class="col-12 col-md-8">主内容区(PC 占 8 列,手机全宽)</div>
<div class="col-12 col-md-4">侧边栏(PC 占 4 列,手机全宽)</div>
</div>
</div>
2. 表单组件
结合 Spring Boot 后端数据绑定:
<form th:action="@{/submit}" method="post">
<div class="mb-3">
<label class="form-label">用户名</label>
<input type="text" class="form-control" name="username">
</div>
<button type="submit" class="btn btn-primary">提交</button>
</form>
3. 交互组件(模态框)
<!-- 触发按钮 -->
<button class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#confirmModal">删除</button>
<!-- 模态框 -->
<div class="modal fade" id="confirmModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">确认删除</h5>
</div>
<div class="modal-body">确定要删除此项吗?</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
<button type="button" class="btn btn-danger">确认删除</button>
</div>
</div>
</div>
</div>
五、自定义 Bootstrap 样式
1. 覆盖默认变量
创建自定义 CSS 文件(如 custom.css
):
/* 修改主题色 */
:root {
--bs-primary: #2c3e50;
--bs-success: #18bc9c;
}
/* 自定义按钮样式 */
.btn-custom {
border-radius: 20px;
padding: 10px 25px;
}
2. 引入自定义文件
在模板中加载自定义样式:
<link th:href="@{/css/custom.css}" rel="stylesheet">
六、常见问题与解决
1. 样式未生效
• 检查路径:确保 CSS/JS 文件路径正确(可通过浏览器开发者工具查看 Network 请求)。
• 缓存问题:强制刷新页面(Ctrl + F5
)。
2. 组件交互失效
• 依赖缺失:Bootstrap 5 需引入 bootstrap.bundle.min.js
(包含 Popper.js),Bootstrap 4 需额外引入 jQuery。
3. 响应式布局错位
• 正确使用网格类:确保 .row
和 .col-*
嵌套在 .container
或 .container-fluid
中。
七、资源推荐
• 官方文档:
• 免费模板1:
• 免费模板2:
• 图标库:
总结
Bootstrap 模板通过预定义的 CSS 类和 JavaScript 插件,极大简化了前端开发流程。在 Spring Boot 项目中,只需将静态资源放入 static/
目录或使用 CDN 链接,即可快速构建现代化、响应式的用户界面。结合 Thymeleaf 的动态数据绑定,能轻松实现前后端分离的开发模式。
12 bootstrap和vue区别
Bootstrap 和 Vue.js 是前端开发中两个不同定位的技术工具,分别专注于 UI 样式框架 和 交互逻辑框架。
一、核心定位与功能对比
特性 | Bootstrap | Vue.js |
---|---|---|
类型 | CSS/UI 框架 | JavaScript 框架 |
主要用途 | 快速构建 响应式页面布局和视觉样式 | 构建 动态交互式单页应用(SPA) |
核心能力 | 预置样式、组件(按钮、表格、导航栏等) | 数据驱动视图、组件化、状态管理、路由、虚拟 DOM |
依赖关系 | 依赖 jQuery(Bootstrap 4 及之前) | 无硬性依赖,可独立使用或配合其他库(如 Vuex) |
学习曲线 | 低(主要掌握 CSS 类名和布局规则) | 中高(需理解数据绑定、组件通信等概念) |
典型项目场景 | 企业官网、管理后台、静态页面 | 复杂 SPA(如社交平台、实时协作工具) |
二、技术细节对比
1. 核心功能
• Bootstrap
• 预定义 CSS 类:如 .btn
, .table-striped
,通过类名快速实现样式。
• 响应式布局系统:基于栅格(Grid System)实现多设备适配。
• JavaScript 插件:如模态框(Modal)、轮播图(Carousel),依赖 jQuery。
• Vue.js
• 响应式数据绑定:数据变化自动更新视图(如 v-model
双向绑定)。
• 组件化开发:将 UI 拆分为独立组件(.vue
文件),支持复用和状态管理。
• 生态系统:Vue Router(路由)、Vuex(状态管理)、Vite(构建工具)等。
2. 代码示例对比
• Bootstrap(HTML + CSS 类)
<!-- 按钮组件 -->
<button class="btn btn-primary">提交</button>
<!-- 响应式栅格 -->
<div class="row">
<div class="col-md-8">主内容</div>
<div class="col-md-4">侧边栏</div>
</div>
• Vue.js(数据驱动 + 组件)
<template>
<div>
<!-- 动态列表渲染 -->
<ul>
<li v-for="item in items" :key="item.id">{{ item.text }}</li>
</ul>
<!-- 事件绑定 -->
<button @click="submitForm">提交</button>
</div>
</template>
<script>
export default {
data() {
return { items: [{ id: 1, text: '项目1' }, { id: 2, text: '项目2' }] };
},
methods: {
submitForm() { /* 处理逻辑 */ }
}
};
</script>
三、适用场景分析
1. 使用 Bootstrap 的场景
• 快速原型开发:需要在短时间内完成一个视觉统一的网站。
• 静态内容展示:企业官网、产品介绍页等以内容呈现为主的场景。
• 传统多页应用:结合服务端渲染(如 Spring Boot + Thymeleaf)。
2. 使用 Vue.js 的场景
• 复杂交互应用:需要实时更新数据的后台系统(如数据看板)。
• 单页应用(SPA):用户频繁操作且无需刷新页面的应用(如在线编辑器)。
• 组件化需求:项目中存在大量可复用的 UI 模块或业务逻辑。
四、协同使用方案
虽然 Bootstrap 和 Vue.js 定位不同,但它们可以结合使用以发挥各自优势:
1. 直接整合
• Bootstrap 处理样式:使用 Bootstrap 的 CSS 类定义外观。
• Vue 处理交互:通过 Vue 实现动态数据绑定和事件处理。
<template>
<div class="container">
<button class="btn btn-primary" @click="handleClick">点击次数:{{ count }}</button>
</div>
</template>
2. 使用专为 Vue 封装的 Bootstrap 库
• BootstrapVue:提供 Vue 组件化封装的 Bootstrap 元素(如 <b-button>
)。
<template>
<b-button variant="primary" @click="submit">提交</b-button>
</template>
五、总结
• Bootstrap:适合 快速构建视觉一致、响应式的静态页面,降低 UI 设计门槛。
• Vue.js:适合 开发数据驱动、高交互性的动态应用,提升代码组织和维护性。
• 组合使用:Bootstrap 负责“外观”,Vue 负责“行为”,二者互补可覆盖从简单到复杂的前端需求。