使用IntelliJ IDEA和Maven搭建SpringBoot集成Fastjson项目

发布于:2025-07-19 ⋅ 阅读:(12) ⋅ 点赞:(0)

使用IntelliJ IDEA和Maven搭建SpringBoot集成Fastjson项目

下面我将详细介绍如何在IntelliJ IDEA中使用Maven搭建一个集成Fastjson的SpringBoot项目,包含完整的环境配置和代码实现。

一、环境准备

  1. 软件要求
  • IntelliJ IDEA 2021.x或更高版本
  • JDK 1.8或更高版本(推荐JDK 11/17)
  • Maven 3.6+
  • Git (可选)
  1. 检查环境
java -version
mvn -v 

二、创建项目

  1. 使用IDEA创建SpringBoot项目

  2. 打开IntelliJ IDEA,选择"File" → “New” → “Project”

  3. 在左侧选择"Spring Initializr"

  4. 配置项目基本信息:

    • Name: springboot-fastjson-demo
    • Location: 选择项目存储路径
    • Type: Maven
    • Language: Java
    • Group: com.example
    • Artifact: demo
    • Package name: com.example.demo
    • Java version: 选择与本地匹配的版本(推荐11或17)
  5. 点击"Next"

  6. 选择依赖
    在"Dependencies"页面:

  7. 搜索并添加:

    • Spring Web
    • Lombok (可选,简化代码)
  8. 点击"Next" → “Finish”

三、配置Fastjson

  1. 添加Fastjson依赖

打开pom.xml,在<dependencies>部分添加:

<!-- Fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>2.0.25</version> <!-- 使用最新稳定版本 -->
</dependency>
  1. 完整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>

四、项目结构配置

  1. 创建包结构
src/main/java/com/example/demo/
├── config/       # 配置类
├── controller/   # 控制器 
├── model/        # 数据模型 
└── service/      # 服务层(可选)
  1. 配置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);
    }
}

五、创建模型和控制器

  1. 创建模型类

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;
    }
}
  1. 创建控制器

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;
    }
}

六、安全配置

  1. 禁用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.");
}

七、运行和测试

  1. 启动应用

运行DemoApplication中的main方法

  1. 测试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测试:

  1. GET请求: http://localhost:8080/api/users/1
  2. 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 {
    
    @Test
    void 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());
    }
}

九、常见问题解决

  1. 中文乱码问题:

    • 确保配置了正确的字符集: fastJsonConfig.setCharset(StandardCharsets.UTF_8);
  2. 日期格式化问题:

    • 检查日期格式配置: fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
  3. 循环引用问题:

    • 启用禁用循环引用检测: SerializerFeature.DisableCircularReferenceDetect
  4. 依赖冲突问题:

    • 如果同时存在Jackson和Fastjson,确保Fastjson优先级更高
    • 可以在application.properties中添加: spring.http.converters.preferred-json-mapper=fastjson

通过以上步骤,您已经成功在IntelliJ IDEA中使用Maven搭建了一个集成Fastjson的SpringBoot项目,并进行了基本的安全配置。


网站公告

今日签到

点亮在社区的每一天
去签到