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/mydbusername: rootpassword: 123456jpa:hibernate:ddl-auto: updateshow-sql: true
2. Redis 緩存使用
@Service
public class UserService {@Autowiredprivate 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 {@Beanpublic 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 {@Overridepublic 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-linestring with line breaks.single-line: >This is a single-linestring 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: 8080ssl: enabled: truekey-store: "keystore.p12"
5. 常見應用示例
Spring Boot配置
server:port: 8080servlet:context-path: /apispring:datasource:url: jdbc:mysql://localhost:3306/mydbusername: rootpassword: "123456"logging:level:org.springframework: INFO
? 文件擴展名:.yml
或 .yaml
(兩者等價)。
6. 核心區別
特性 | YAML(.yml) | Properties |
---|---|---|
數據結構 | 支持嵌套層級(通過縮進或符號)。 | 扁平結構,通過. 模擬層級。 |
語法 | 縮進敏感(必須用空格),冒號: 分隔鍵值。 | 等號= 或冒號: 分隔鍵值,無縮進。 |
可讀性 | 高(層次清晰,適合復雜配置)。 | 較低(長鍵名易冗余)。 |
數據類型支持 | 自動推斷類型(字符串、布爾、數字、列表、對象)。 | 所有值均為字符串,需手動轉換類型。 |
高級功能 | 支持錨點(& )、引用(* )、多行文本等。 | 僅支持鍵值對和簡單注釋。 |
注釋 | 使用 # 。 | 使用 # 或 ! 。 |
重復鍵處理 | 不允許重復鍵(覆蓋或報錯)。 | 允許重復鍵(最后一個生效)。 |
7. 語法對比示例
YAML 示例
# 支持嵌套對象和列表
server:port: 8080ssl: enabled: truespring:datasource:url: jdbc:mysql://localhost:3306/mydbusername: root
Properties 示例
# 扁平化結構,用`.`表示層級
server.port=8080
server.ssl.enabled=truespring.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: 25address:city: "Shanghai"zip: 200000hobbies:- 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> {@Overridepublic boolean isValid(String value, ConstraintValidatorContext context) {return value != null && value.matches("^1[3-9]\\d{9}$");}
}
使用自定義注解:
public class User {@PhoneNumberprivate 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: 8080ssl:enabled: truespring:datasource:url: jdbc:mysql://prod-db:3306/mydbusername: 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: 8081spring:datasource:url: jdbc:mysql://localhost:3306/dev_dbusername: dev_userpassword: dev_pass
3.4 生產環境配置(application-prod.yml
)
server:port: 8080spring:datasource:url: jdbc:mysql://prod-db:3306/prod_dbusername: prod_userpassword: 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 {@Overridepublic 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: truepath: /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 {// 添加攔截器@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/admin/**");}// 自定義視圖控制器@Overridepublic 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 {@Overrideprotected 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 {@Overridepublic 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 負責“行為”,二者互補可覆蓋從簡單到復雜的前端需求。
13 WebMvcConfigurer接口
WebMvcConfigurer
是 Spring MVC 中用于自定義 MVC 配置的核心接口,通常通過實現該接口來覆蓋默認的 Spring MVC 行為。
1. 核心作用
? 配置 MVC 行為:例如靜態資源處理、跨域(CORS)、攔截器、視圖解析器、格式化器等。
? 替代舊方案:在 Spring 5+ 中,直接實現 WebMvcConfigurer
(接口有默認方法),取代已廢棄的 WebMvcConfigurerAdapter
類。
2. 常用方法及配置示例
(1) 跨域配置:addCorsMappings()
@Override
public void addCorsMappings(CorsRegistry registry) {registry.addMapping("/api/**").allowedOrigins("https://example.com").allowedMethods("GET", "POST");
}
(2) 靜態資源處理:addResourceHandlers()
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");// 保留默認配置(如Spring Boot的靜態資源路徑)registry.addResourceHandler("/**").addResourceLocations("classpath:/public/");
}
(3) 攔截器配置:addInterceptors()
@Override
public void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new AuthInterceptor()).addPathPatterns("/admin/**");
}
(4) 視圖解析器:configureViewResolvers()
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {InternalResourceViewResolver resolver = new InternalResourceViewResolver();resolver.setPrefix("/WEB-INF/views/");resolver.setSuffix(".jsp");registry.viewResolver(resolver);
}
(5) 格式化與轉換器:addFormatters()
@Override
public void addFormatters(FormatterRegistry registry) {registry.addConverter(new StringToDateConverter());
}
3. 實現方式
創建一個配置類,實現 WebMvcConfigurer
接口,并覆蓋需要的方法:
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {// 覆蓋需要的方法
}
4. 注意事項
? Spring Boot 項目:通常無需 @EnableWebMvc
,否則會禁用自動配置。僅在需要完全控制 MVC 配置時使用。
? 避免覆蓋默認行為:例如,在配置靜態資源時,確保不覆蓋 Spring Boot 的默認路徑(如 /static
、/public
)。
? 方法選擇性覆蓋:接口方法均為默認方法(Java 8+),只需實現需要自定義的方法。
5. 常見用例場景
? 自定義靜態資源路徑:添加新的資源目錄。
? 全局跨域配置:為特定 API 路徑啟用 CORS。
? 添加攔截器:實現權限驗證、日志記錄等。
? 日期格式化:統一全局日期格式。
14 怎么修改spring boot默認配置
在 Spring Boot 中修改默認配置有多種方式,具體取決于需要調整的內容。以下是常見的修改方法及詳細說明:
1. 通過 application.properties
或 application.yml
修改
這是最簡單直接的方式,適用于大多數基礎配置(如端口、數據源、日志等)。Spring Boot 提供了大量預定義的配置屬性。
如何查找可用屬性?
? 查閱 Spring Boot 官方文檔
? 在 IDE 中通過 Ctrl + 點擊
查看配置類的 @ConfigurationProperties
注解(如 ServerProperties
、DataSourceProperties
等)
2. 使用 @Configuration
類覆蓋默認 Bean
對于需要自定義復雜邏輯的配置(如 MVC 攔截器、消息轉換器等),可以通過創建 @Configuration
類并重寫默認 Bean。
示例:覆蓋默認的 Jackson JSON 序列化配置
@Configuration
public class JacksonConfig {@Beanpublic Jackson2ObjectMapperBuilderCustomizer jacksonCustomizer() {return builder -> {builder.serializationInclusion(JsonInclude.Include.NON_NULL); // 忽略 null 字段builder.dateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); // 統一日期格式};}
}
3. 實現 WebMvcConfigurer
接口(針對 MVC 配置)
用于自定義 Spring MVC 的行為(如攔截器、跨域、視圖解析器等),而不破壞 Spring Boot 的自動配置。
示例:添加攔截器
@Configuration
public class WebConfig implements WebMvcConfigurer {@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new LoggingInterceptor()).addPathPatterns("/api/**");}
}
4. 排除自動配置類
如果某個 Spring Boot 自動配置不符合需求,可以通過 @SpringBootApplication
注解排除它。
示例:禁用數據源自動配置
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class MyApplication {public static void main(String[] args) {SpringApplication.run(MyApplication.class, args);}
}
5. 使用 @Conditional
注解自定義條件化配置
通過條件注解(如 @ConditionalOnProperty
、@ConditionalOnMissingBean
)控制 Bean 的加載。
示例:僅在特定環境下啟用配置
@Configuration
@ConditionalOnProperty(name = "feature.cache.enabled", havingValue = "true")
public class CacheConfig {@Beanpublic CacheManager cacheManager() {return new EhCacheCacheManager();}
}
6. 直接覆蓋默認 Bean
如果 Spring Boot 的自動配置類創建了一個 Bean(如 DataSource
),你可以定義自己的 Bean 來覆蓋它。
示例:自定義數據源
@Configuration
public class DataSourceConfig {@Bean@Primarypublic DataSource dataSource() {return DataSourceBuilder.create().url("jdbc:h2:mem:testdb").username("sa").password("").build();}
}
15 用模板搭建一個前后端分類的網站的步驟
以下是使用模板搭建前后端分離網站的具體步驟,后端采用 Java(Spring Boot),前端可選擇任意框架(如 Vue.js、React 或 Angular):
1. 項目規劃
? 目標:明確網站功能(如用戶登錄、數據展示、表單提交)。
? 技術選型:
? 后端:Spring Boot + MyBatis/JPA + MySQL。
? 前端:React/Vue/Angular + Axios(HTTP 請求庫)。
? API 交互:RESTful API,數據格式為 JSON。
? 模板來源:前端模板可從 ThemeForest 或 Bootstrap 官方 獲取。
2. 環境準備
? 后端:
? JDK 17+
? Maven/Gradle
? IDE(IntelliJ IDEA 或 Eclipse)
? MySQL 或 H2(嵌入式數據庫)
? 前端:
? Node.js + npm/yarn
? IDE(VS Code 或 WebStorm)
? 工具:
? Postman(測試 API)
? Git(版本控制)
3. 后端搭建(Spring Boot)
(1) 初始化項目
使用 Spring Initializr 創建項目,勾選依賴:
? Web:Spring Web
? 數據庫:Spring Data JPA
或 MyBatis
? 其他:Lombok
(簡化代碼)
(2) 項目結構
src/
├── main/
│ ├── java/
│ │ └── com.example.demo/
│ │ ├── controller/ # API 接口
│ │ ├── service/ # 業務邏輯
│ │ ├── repository/ # 數據庫操作
│ │ ├── entity/ # 數據模型
│ │ └── DemoApplication.java
│ └── resources/
│ ├── application.yml # 配置文件
│ └── static/ # 可存放前端構建后的文件(可選)
(3) 配置數據庫
# application.yml
spring:datasource:url: jdbc:mysql://localhost:3306/mydb?useSSL=falseusername: rootpassword: 123456jpa:hibernate:ddl-auto: update
(4) 創建 API 接口
// UserController.java
@RestController
@RequestMapping("/api/users")
public class UserController {@Autowiredprivate UserService userService;@GetMappingpublic List<User> getAllUsers() {return userService.findAll();}@PostMappingpublic User createUser(@RequestBody User user) {return userService.save(user);}
}
(5) 啟動后端
運行 DemoApplication.java
,訪問 http://localhost:8080/api/users
驗證 API。
4. 前端搭建(以 Vue.js 為例)
(1) 初始化項目
# 使用 Vue CLI 創建項目
npm install -g @vue/cli
vue create frontend
cd frontend
(2) 集成模板
? 下載 HTML/CSS/JS 模板(如 Bootstrap 模板)。
? 將模板的靜態資源(CSS、JS、圖片)復制到 public/
或 src/assets/
。
? 將 HTML 拆分為 Vue 組件(如 Header.vue
、Footer.vue
)。
(3) 調用后端 API
安裝 Axios:
npm install axios
在組件中調用接口:
// src/components/UserList.vue
<script>
import axios from 'axios';export default {data() {return {users: []};},mounted() {axios.get('http://localhost:8080/api/users').then(response => this.users = response.data);}
};
</script>
(4) 解決跨域問題
在 vue.config.js
中配置代理:
module.exports = {devServer: {proxy: {'/api': {target: 'http://localhost:8080',changeOrigin: true}}}
};
5. 前后端聯調
? 測試 API:使用 Postman 驗證接口正確性。
? 聯調數據:前端通過 Axios 請求后端數據并渲染到模板。
? 統一數據格式:
// 響應格式示例
{"code": 200,"data": [...],"message": "Success"
}
6. 部署
(1) 后端部署
? 打包為 JAR:
mvn clean package
? 運行 JAR:
java -jar target/demo-0.0.1-SNAPSHOT.jar
(2) 前端部署
? 構建靜態文件:
npm run build
? 托管到:
? Nginx:配置反向代理。
? Netlify/Vercel:直接拖入 dist/
文件夾。
7. 安全增強(可選)
? JWT 認證:添加 spring-boot-starter-security
和 Token 驗證。
? HTTPS:使用 Let’s Encrypt 生成免費證書。
? 輸入校驗:在實體類中添加 @NotBlank
、@Email
等注解。
模板示例資源
? 前端模板:
? Vue Admin Template
? React Bootstrap Template
? 后端模板:
? Spring Boot + JPA Starter
常見問題
- 跨域請求失敗
? 后端配置 CORS:@Configuration public class WebConfig implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**").allowedOrigins("http://localhost:3000").allowedMethods("*");} }
- 數據庫連接超時
? 檢查application.yml
中的數據庫地址和權限。 - 靜態資源加載失敗
? 確保前端構建后的文件路徑正確(如publicPath: '/'
)。
通過以上步驟,你可以快速搭建一個基于模板的前后端分離網站,后端使用 Java(Spring Boot),前端自由選擇框架。