使用IntelliJ IDEA和Maven搭建SpringBoot集成Fastjson項目
下面我將詳細介紹如何在IntelliJ IDEA中使用Maven搭建一個集成Fastjson的SpringBoot項目,包含完整的環境配置和代碼實現。
一、環境準備
- 軟件要求
- IntelliJ IDEA 2021.x或更高版本
- JDK 1.8或更高版本(推薦JDK 11/17)
- Maven 3.6+
- Git (可選)
- 檢查環境
java -version
mvn -v
二、創建項目
-
使用IDEA創建SpringBoot項目
-
打開IntelliJ IDEA,選擇"File" → “New” → “Project”
-
在左側選擇"Spring Initializr"
-
配置項目基本信息:
- Name: springboot-fastjson-demo
- Location: 選擇項目存儲路徑
- Type: Maven
- Language: Java
- Group: com.example
- Artifact: demo
- Package name: com.example.demo
- Java version: 選擇與本地匹配的版本(推薦11或17)
-
點擊"Next"
-
選擇依賴
在"Dependencies"頁面: -
搜索并添加:
- Spring Web
- Lombok (可選,簡化代碼)
-
點擊"Next" → “Finish”
三、配置Fastjson
- 添加Fastjson依賴
打開pom.xml
,在<dependencies>
部分添加:
<!-- Fastjson -->
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>2.0.25</version> <!-- 使用最新穩定版本 -->
</dependency>
- 完整pom.xml示例
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.0</version> <!-- 使用最新穩定版 --><relativePath/></parent><groupId>com.example</groupId><artifactId>demo</artifactId><version>0.0.1-SNAPSHOT</version><name>springboot-fastjson-demo</name><description>Demo project for Spring Boot with Fastjson</description><properties><java.version>11</java.version></properties><dependencies><!-- Spring Boot Starter Web --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- Fastjson --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>2.0.25</version></dependency><!-- Lombok --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><!-- Test --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><excludes><exclude><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></exclude></excludes></configuration></plugin></plugins></build></project>
四、項目結構配置
- 創建包結構
src/main/java/com/example/demo/
├── config/ # 配置類
├── controller/ # 控制器
├── model/ # 數據模型
└── service/ # 服務層(可選)
- 配置Fastjson為默認JSON處理器
創建FastJsonConfig.java
:
package com.example.demo.config;import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;@Configuration
public class FastJsonConfig implements WebMvcConfigurer {@Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {// 1.創建FastJson消息轉換器FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();// 2.創建FastJson配置 FastJsonConfig fastJsonConfig = new FastJsonConfig();fastJsonConfig.setCharset(StandardCharsets.UTF_8);// 3.配置序列化特性 fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat, // 格式化輸出SerializerFeature.WriteMapNullValue, // 輸出空字段SerializerFeature.WriteNullListAsEmpty, // 空列表輸出[]而非null SerializerFeature.DisableCircularReferenceDetect // 禁止循環引用 );// 4.日期格式fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");// 5.處理中文亂碼 List<MediaType> fastMediaTypes = new ArrayList<>();fastMediaTypes.add(MediaType.APPLICATION_JSON);fastConverter.setSupportedMediaTypes(fastMediaTypes);// 6.注入配置 fastConverter.setFastJsonConfig(fastJsonConfig);// 7.添加到轉換器列表,并優先使用converters.add(0, fastConverter);}
}
五、創建模型和控制器
- 創建模型類
User.java
:
package com.example.demo.model;import lombok.Data;@Data
public class User {private Long id;private String username;private Integer age;private String email;// 空構造器是Fastjson反序列化必需的 public User() {}public User(Long id, String username, Integer age) {this.id = id;this.username = username;this.age = age;}
}
- 創建控制器
UserController.java
:
package com.example.demo.controller;import com.alibaba.fastjson.JSON;
import com.example.demo.model.User;
import org.springframework.web.bind.annotation.*;@RestController
@RequestMapping("/api/users")
public class UserController {@GetMapping("/{id}")public User getUser(@PathVariable Long id) {User user = new User(id, "測試用戶", 25);// 測試Fastjson序列化 String json = JSON.toJSONString(user);System.out.println("序列化結果: " + json);return user;}@PostMapping public User createUser(@RequestBody User user) {System.out.println("收到用戶: " + user);// 在實際應用中,這里會保存用戶到數據庫 return user;}
}
六、安全配置
- 禁用AutoType功能
在FastJsonConfig.java
中添加:
import com.alibaba.fastjson.parser.ParserConfig;
import javax.annotation.PostConstruct;// 在FastJsonConfig類中添加
@PostConstruct
public void init() {// 禁用AutoType功能(安全考慮)ParserConfig.getGlobalInstance().setAutoTypeSupport(false);// 或者啟用安全模式(更嚴格)// ParserConfig.getGlobalInstance().setSafeMode(true);// 設置白名單ParserConfig.getGlobalInstance().addAccept("com.example.demo.model.");
}
七、運行和測試
- 啟動應用
運行DemoApplication
中的main方法
- 測試API
使用curl測試:
獲取用戶
curl http://localhost:8080/api/users/1創建用戶
curl -X POST http://localhost:8080/api/users \-H "Content-Type: application/json" \-d '{"id":2,"username":"新用戶","age":30}'
使用Postman測試:
- GET請求:
http://localhost:8080/api/users/1
- POST請求:
http://localhost:8080/api/users
- Body → raw → JSON
- 輸入:
{"id":2,"username":"新用戶","age":30}
八、驗證Fastjson配置
創建測試類驗證配置是否生效:
package com.example.demo;import com.alibaba.fastjson.JSON;
import com.example.demo.model.User;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;import static org.junit.jupiter.api.Assertions.*;@SpringBootTest
class DemoApplicationTests {@Testvoid testFastjsonSerialization() {User user = new User(1L, "測試", 20);String json = JSON.toJSONString(user);assertTrue(json.contains("\"username\":\"測試\""));User parsedUser = JSON.parseObject(json, User.class);assertEquals(user.getUsername(), parsedUser.getUsername());}
}
九、常見問題解決
-
中文亂碼問題:
- 確保配置了正確的字符集:
fastJsonConfig.setCharset(StandardCharsets.UTF_8);
- 確保配置了正確的字符集:
-
日期格式化問題:
- 檢查日期格式配置:
fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
- 檢查日期格式配置:
-
循環引用問題:
- 啟用禁用循環引用檢測:
SerializerFeature.DisableCircularReferenceDetect
- 啟用禁用循環引用檢測:
-
依賴沖突問題:
- 如果同時存在Jackson和Fastjson,確保Fastjson優先級更高
- 可以在
application.properties
中添加:spring.http.converters.preferred-json-mapper=fastjson
通過以上步驟,您已經成功在IntelliJ IDEA中使用Maven搭建了一個集成Fastjson的SpringBoot項目,并進行了基本的安全配置。