当前位置: 首页 > news >正文

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

使用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 {@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());}
}

九、常见问题解决

  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项目,并进行了基本的安全配置。

http://www.dtcms.com/a/284277.html

相关文章:

  • 【git】使用教程
  • CommonJS和ES模块区别对比
  • API开发提速新方案:SmartBear API Hub与ReadyAPI虚拟化整合实践
  • ESP8266服务器建立TCP连接失败AT+CIPSTART=“TCP“,“192.168.124.1“,8080 ERROR CLOSED
  • JAVA后端开发——success(data) vs toAjax(rows): 何时用
  • 美拍sig逆向
  • 神经网络:模拟人脑的 AI 信息处理系统
  • 代码随想录打卡第十二天
  • Unity | AmplifyShaderEditor插件基础(第十集:噪声的种类+火焰制作-下)
  • 透过结构看时间——若思考清洗则表达有力
  • 开源Agent平台Dify源码剖析系列(六)核心模块core/agent之CotCompletionAgentRunner
  • Web开发 01
  • Vue.js 的 Composition API 深度解析:构建高效可维护的前端逻辑
  • 让大模型输出更加规范化——指定插件
  • LVS部署DR模式集群
  • @Linux搭建DNS-主从服务器
  • Spring原理揭秘--Spring的AOP
  • cuda编程笔记(8)--线程束warp
  • Cookie 与 Session概述
  • AI编程实战:如何让AI生成带参数和返回值的Python函数——以PDF文本提取为例
  • 【橘子分布式】gRPC(理论篇)
  • 要实现在调用  driver.get()  后立即阻止页面自动跳转到 Azure 登录页,可通过以下几种方法实现:
  • Redis完全指南:从基础到实战(含缓存问题、布隆过滤器、持久化及Spring Boot集成)
  • 前端 cookie 使用
  • 独家|理想汽车放弃华为PBC模式,回归OKR理想汽车
  • 自动化测试工具 Selenium 入门指南
  • 大带宽服务器对于高流量网站的作用
  • Kubernetes v1.33:容器生命周期管理的重要演进
  • 断网情况下,网线直连 Windows 笔记本 和Ubuntu 服务器
  • python的抗洪救灾管理系统