Loading... 以下是一份严谨的Spring Boot + MyBatis + Vue全栈开发实践指南,结合2023年最新技术栈: --- ### 一、技术栈架构设计 ```mermaid graph TB A[Vue3前端] -->|Axios请求| B[Spring Boot 3.x] B -->|MyBatis-Plus| C[MySQL 8.0] B -->|Redis缓存| D[Redis 7.0] A -->|Vite构建| E[CDN部署] ``` --- ### 二、环境搭建(2023推荐版本) | **组件** | **版本** | **作用** | | -------------- | -------------- | ------------------- | | JDK | 17+ | Spring Boot运行环境 | | Node.js | 18.x LTS | Vue开发环境 | | MyBatis-Plus | 3.5.3.1 | 增强ORM功能 | | Vue-Router | 4.x | 前端路由管理 | | Pinia | 2.x | 状态管理替代Vuex | > 💡 注:Spring Boot 3.x强制要求JDK 17+,Vue3推荐Pinia替代Vuex --- ### 三、Spring Boot整合MyBatis-Plus #### 1. 数据源配置(application.yml) ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/demo?useSSL=false&serverTimezone=Asia/Shanghai username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver mybatis-plus: configuration: map-underscore-to-camel-case: true # 自动驼峰转换 global-config: db-config: logic-delete-field: deleted # 逻辑删除字段 ``` #### 2. MyBatis-Plus实体类与Mapper ```java // 实体类(使用Lombok) @Data @TableName("sys_user") public class User { @TableId(type = IdType.AUTO) private Long id; private String username; private String password; @TableLogic // 逻辑删除注解 private Integer deleted; } // Mapper接口(继承BaseMapper) @Mapper public interface UserMapper extends BaseMapper<User> {} ``` #### 3. 服务层实现 ```java @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { // 自定义查询方法 public User getUserWithRoles(Long userId) { return baseMapper.selectUserWithRoles(userId); // 需在XML定义SQL } } ``` --- ### 四、Vue3前端工程实践 #### 1. Vite项目创建 ```bash npm create vite@latest my-project -- --template vue-ts ``` #### 2. API请求封装(axios) ```typescript // src/utils/request.ts import axios from 'axios'; const service = axios.create({ baseURL: import.meta.env.VITE_API_URL, // 环境变量配置 timeout: 10000 }); // 请求拦截器(添加Token) service.interceptors.request.use(config => { const token = localStorage.getItem('token'); if (token) { config.headers.Authorization = `Bearer ${token}`; } return config; }); export default service; ``` #### 3. Pinia状态管理 ```typescript // src/stores/user.ts import { defineStore } from 'pinia'; export const useUserStore = defineStore('user', { state: () => ({ userInfo: null as UserInfo | null, token: '' }), actions: { async login(username: string, password: string) { const res = await request.post('/api/login', { username, password }); this.token = res.data.token; this.userInfo = res.data.user; } } }); ``` --- ### 五、前后端数据交互流程 ```mermaid sequenceDiagram Vue->>Spring Boot: POST /api/login (JSON) Spring Boot->>MyBatis: 执行SQL查询 MyBatis->>MySQL: SELECT * FROM user MySQL-->>MyBatis: 返回用户数据 MyBatis-->>Spring Boot: 组装User对象 Spring Boot->>Vue: {token:xxx, user:{...}} Vue->>Pinia: 存储登录状态 Vue->>LocalStorage: 持久化Token ``` --- ### 六、关键问题解决方案 #### 1. 跨域处理(Spring Boot配置) ```java @Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://localhost:5173") // Vite默认端口 .allowedMethods("*") .allowCredentials(true); } } ``` #### 2. MyBatis动态SQL示例 ```xml <!-- 根据条件查询用户 --> <select id="selectByCondition" resultType="User"> SELECT * FROM sys_user <where> <if test="username != null"> AND username LIKE CONCAT('%',#{username},'%') </if> <if test="status != null"> AND status = #{status} </if> </where> </select> ``` #### 3. Vue路由守卫 ```typescript // 路由权限控制 router.beforeEach((to, from) => { const store = useUserStore(); if (to.meta.requiresAuth && !store.token) { return '/login'; // 重定向到登录页 } }) ``` --- ### 七、性能优化策略 | **层级** | **优化手段** | **效果** | | -------------- | ------------------------- | --------------- | | 前端 | 组件懒加载 + Vite按需编译 | 减少首屏加载50% | | 网络传输 | Gzip压缩 + HTTP2 | 减少带宽消耗60% | | 后端 | Redis缓存热点数据 | 降低DB压力70% | | SQL | 覆盖索引 + 批量操作 | 查询提速5-10倍 | --- ### 八、部署实践 #### 1. 后端部署命令 ```bash # 打包Spring Boot应用 mvn clean package -DskipTests # 运行Jar包(生产环境) java -jar -Xmx1024m target/demo.jar --spring.profiles.active=prod ``` #### 2. 前端部署(Nginx配置) ```nginx server { listen 80; server_name yourdomain.com; location / { root /var/www/vue-dist; # Vue打包目录 try_files $uri $uri/ /index.html; # 支持history模式 } location /api/ { proxy_pass http://127.0.0.1:8080; # 后端地址 proxy_set_header Host $host; } } ``` --- ### 九、2023最佳实践建议 1. 接口安全:Spring Security整合JWT 2. API文档:Knife4j替代Swagger UI 3. 前端优化:Vue3 `<script setup>`语法 4. 数据同步:WebSocket实时更新 5. 错误监控:Sentry前端异常捕获 > 🚀 **技术趋势**:2023年Volar成为Vue官方推荐IDE插件,MyBatis-Flex作为新型ORM框架性能提升40%,Spring Boot 3.1支持虚拟线程大幅提升并发能力。 最后修改:2025 年 07 月 06 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 如果觉得我的文章对你有用,请随意赞赏