ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

SpringBoot3+微信小程序+Vue3全栈助农商城开发实战

SpringBoot3+微信小程序+Vue3全栈助农商城开发实战 在实际 Java Web 项目开发中一个完整的助农扶贫商城系统需要同时兼顾后端业务逻辑、前端用户体验和移动端便捷性。SpringBoot3 提供了现代化的后端开发体验Spring AI 为智能推荐和客服对话提供了可能原生微信小程序覆盖了移动端用户Vue3 则能构建功能丰富的管理后台。这套技术栈组合既能满足毕业设计的复杂度要求也适合作为实际项目练手。但真正开始编码前很多开发者会卡在环境配置、多端联调和生产部署上。本文将以一个可运行的助农扶贫商城为例带你完成从技术选型、环境搭建、核心功能实现到部署上线的全过程。1. 理解助农扶贫商城的业务模块和技术栈选型助农扶贫商城不同于普通电商需要特别关注农产品特性、扶贫政策对接和农户管理。典型功能包括商品展示、在线购买、订单管理、农户入驻、扶贫数据统计和智能客服。1.1 业务模块拆解用户端微信小程序商品浏览、搜索、下单、支付、个人中心、收货地址管理。农户端管理后台商品上架、订单处理、销售统计、库存管理。平台管理端Vue3后台用户管理、农户审核、订单监控、数据报表、扶贫数据统计。智能服务Spring AI商品推荐、智能客服、扶贫政策问答。1.2 技术栈选型理由SpringBoot3提供现代Java开发体验内置依赖管理、自动配置和监控端点。Spring AI集成AI能力避免从零搭建推荐系统和对话机器人。原生微信小程序直接使用微信生态能力登录、支付、分享性能优于跨端框架。Vue3 Element Plus管理后台需要丰富交互Vue3的组合式API更适合复杂状态管理。1.3 项目结构规划farm-mall/ ├── farm-mall-backend/ # SpringBoot3后端 │ ├── src/main/java/com/farmmall/ │ │ ├── controller/ # 控制器 │ │ ├── service/ # 业务层 │ │ ├── mapper/ # 数据层 │ │ ├── entity/ # 实体类 │ │ └── config/ # 配置类 │ ├── src/main/resources/ │ │ ├── application.yml # 主配置 │ │ └── application-dev.yml # 开发环境配置 │ └── pom.xml # Maven依赖 ├── farm-mall-miniprogram/ # 微信小程序 │ ├── pages/ # 页面文件 │ ├── components/ # 自定义组件 │ ├── utils/ # 工具类 │ └── app.json # 小程序配置 └── farm-mall-admin/ # Vue3管理后台 ├── src/ │ ├── views/ # 页面组件 │ ├── components/ # 通用组件 │ ├── api/ # 接口调用 │ └── store/ # 状态管理 ├── public/ # 静态资源 └── package.json # 依赖配置2. 后端环境准备与核心配置后端使用 SpringBoot3 需要 JDK17这是与 SpringBoot2.x 的主要区别。同时要配置数据库连接、Redis缓存和微信支付参数。2.1 开发环境要求环境版本要求验证命令JDK17java -versionMaven3.6mvn -vMySQL8.0mysql --versionRedis6.0redis-cli --version2.2 Maven依赖配置SpringBoot3 的 parent POM 和 starter 依赖与之前版本有差异需要特别注意?xml version1.0 encodingUTF-8? project xmlnshttp://maven.apache.org/POM/4.0.0 xmlns:xsihttp://www.w3.org/2001/XMLSchema-instance xsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd modelVersion4.0.0/modelVersion parent groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-parent/artifactId version3.2.0/version relativePath/ /parent groupIdcom.farmmall/groupId artifactIdfarm-mall-backend/artifactId version1.0.0/version properties maven.compiler.source17/maven.compiler.source maven.compiler.target17/maven.compiler.target project.build.sourceEncodingUTF-8/project.build.sourceEncoding /properties dependencies !-- Web基础 -- dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-web/artifactId /dependency !-- 数据库相关 -- dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-data-jpa/artifactId /dependency dependency groupIdcom.mysql/groupId artifactIdmysql-connector-j/artifactId version8.2.0/version /dependency !-- Redis缓存 -- dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-data-redis/artifactId /dependency !-- Spring AI (需要添加Spring Milestone仓库) -- dependency groupIdorg.springframework.ai/groupId artifactIdspring-ai-openai-spring-boot-starter/artifactId version0.7.1/version /dependency !-- 微信支付SDK -- dependency groupIdcom.github.wechatpay-apiv3/groupId artifactIdwechatpay-apache-httpclient/artifactId version0.4.7/version /dependency !-- 工具类 -- dependency groupIdorg.apache.commons/groupId artifactIdcommons-lang3/artifactId /dependency /dependencies /project注意Spring AI 目前还处于快速迭代阶段版本号变化较快。实际项目中需要查看官方文档确认最新稳定版本。2.3 数据库表结构设计助农商城的核心表包括用户、商品、订单、农户等需要体现扶贫特色-- 用户表小程序用户 CREATE TABLE user ( id bigint NOT NULL AUTO_INCREMENT, openid varchar(64) NOT NULL COMMENT 微信openid, nickname varchar(100) COMMENT 昵称, avatar_url varchar(500) COMMENT 头像, phone varchar(20) COMMENT 手机号, is_farmer tinyint DEFAULT 0 COMMENT 是否是农户 0-否 1-是, create_time datetime DEFAULT CURRENT_TIMESTAMP, update_time datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (id), UNIQUE KEY uk_openid (openid) ) ENGINEInnoDB DEFAULT CHARSETutf8mb4; -- 商品表重点体现农产品属性 CREATE TABLE product ( id bigint NOT NULL AUTO_INCREMENT, farmer_id bigint NOT NULL COMMENT 农户ID, name varchar(200) NOT NULL COMMENT 商品名称, description text COMMENT 商品描述, price decimal(10,2) NOT NULL COMMENT 价格, stock int NOT NULL DEFAULT 0 COMMENT 库存, category varchar(50) COMMENT 品类蔬菜、水果、粮油等, origin varchar(100) COMMENT 产地, is_organic tinyint DEFAULT 0 COMMENT 是否有机 0-否 1-是, images json COMMENT 商品图片JSON数组, status tinyint DEFAULT 1 COMMENT 状态 0-下架 1-上架, create_time datetime DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id), KEY idx_farmer (farmer_id), KEY idx_category (category) ) ENGINEInnoDB DEFAULT CHARSETutf8mb4; -- 订单表记录扶贫相关数据 CREATE TABLE order ( id bigint NOT NULL AUTO_INCREMENT, order_no varchar(32) NOT NULL COMMENT 订单号, user_id bigint NOT NULL COMMENT 用户ID, total_amount decimal(10,2) NOT NULL COMMENT 订单总金额, pay_amount decimal(10,2) NOT NULL COMMENT 实际支付金额, status tinyint NOT NULL DEFAULT 0 COMMENT 订单状态 0-待支付 1-已支付 2-已发货 3-已完成 4-已取消, farmer_income decimal(10,2) COMMENT 农户实际收入平台可能补贴, platform_subsidy decimal(10,2) DEFAULT 0 COMMENT 平台补贴金额, address json NOT NULL COMMENT 收货地址JSON, create_time datetime DEFAULT CURRENT_TIMESTAMP, pay_time datetime COMMENT 支付时间, PRIMARY KEY (id), UNIQUE KEY uk_order_no (order_no), KEY idx_user (user_id), KEY idx_create_time (create_time) ) ENGINEInnoDB DEFAULT CHARSETutf8mb4;2.4 关键配置详解application.yml 中需要配置数据库、Redis、微信支付和Spring AI参数spring: application: name: farm-mall datasource: url: jdbc:mysql://localhost:3306/farm_mall?useUnicodetruecharacterEncodingutf8serverTimezoneAsia/Shanghai username: root password: your_password driver-class-name: com.mysql.cj.jdbc.Driver jpa: hibernate: ddl-auto: update show-sql: true data: redis: host: localhost port: 6379 password: database: 0 ai: openai: api-key: ${OPENAI_API_KEY:sk-demo} base-url: https://api.openai.com/v1 # 微信支付配置 wechat: pay: app-id: wx1234567890abcdef mch-id: 1230000100 api-v3-key: your_api_v3_key private-key-path: classpath:apiclient_key.pem serial-no: your_serial_no # 日志配置查看SQL日志 logging: level: com.farmmall.mapper: DEBUG org.hibernate.SQL: DEBUG org.hibernate.type.descriptor.sql.BasicBinder: TRACE生产环境中敏感配置如数据库密码、API密钥等应该使用环境变量或配置中心管理不要直接写在配置文件中。3. 核心业务功能实现助农商城后端需要实现用户认证、商品管理、订单处理和智能推荐等核心功能。3.1 微信用户登录集成微信小程序用户登录流程涉及 code 交换 openid需要妥善处理会话管理RestController RequestMapping(/api/auth) public class AuthController { Autowired private UserService userService; PostMapping(/wxlogin) public ResultLoginVO wxLogin(RequestBody LoginDTO loginDTO) { // 1. 用code换取openid String openid wechatService.getOpenid(loginDTO.getCode()); if (StringUtils.isBlank(openid)) { return Result.error(微信登录失败); } // 2. 查询或创建用户 User user userService.findOrCreateByOpenid(openid, loginDTO.getUserInfo()); // 3. 生成JWT token String token jwtUtil.generateToken(user.getId()); // 4. 返回用户信息和token LoginVO vo new LoginVO(); vo.setToken(token); vo.setUser(user); return Result.success(vo); } } Service public class WechatService { public String getOpenid(String code) { String url https://api.weixin.qq.com/sns/jscode2session ?appid appId secret appSecret js_code code grant_typeauthorization_code; // 使用RestTemplate或HttpClient调用微信接口 String response restTemplate.getForObject(url, String.class); WechatSessionResponse session JSON.parseObject(response, WechatSessionResponse.class); if (session.getErrcode() ! null session.getErrcode() ! 0) { log.error(微信登录失败: {}, session.getErrmsg()); return null; } return session.getOpenid(); } }3.2 商品推荐与Spring AI集成利用Spring AI实现基于用户行为的商品推荐Service public class ProductRecommendService { Autowired private OpenAiChatClient chatClient; Autowired private ProductService productService; public ListProduct recommendProducts(Long userId, int limit) { // 1. 获取用户历史行为 ListProduct historyProducts productService.getUserBrowseHistory(userId); if (historyProducts.isEmpty()) { // 没有历史记录时返回热门商品 return productService.getHotProducts(limit); } // 2. 构建推荐提示词 String prompt buildRecommendPrompt(historyProducts, limit); // 3. 调用AI获取推荐结果 String response chatClient.call(prompt); // 4. 解析AI返回的商品ID列表 ListLong recommendedIds parseRecommendationResponse(response); // 5. 查询商品详情 return productService.getProductsByIds(recommendedIds); } private String buildRecommendPrompt(ListProduct historyProducts, int limit) { StringBuilder sb new StringBuilder(); sb.append(根据用户浏览过的农产品); for (Product product : historyProducts) { sb.append(product.getName()).append(品类).append(product.getCategory()).append(); } sb.append(请推荐).append(limit).append(个相关的农产品。) .append(只返回商品ID列表用逗号分隔不要其他内容。); return sb.toString(); } }3.3 订单支付流程实现微信支付需要处理预支付订单生成、支付结果回调等关键环节Service public class OrderService { Autowired private WechatPayService wechatPayService; public PrepayResponse createPrepayOrder(Long orderId, String openid) { Order order orderMapper.selectById(orderId); if (order null) { throw new BusinessException(订单不存在); } // 创建微信支付预订单 PrepayRequest request new PrepayRequest(); request.setAppid(wechatConfig.getAppId()); request.setMchid(wechatConfig.getMchId()); request.setDescription(助农商城订单- order.getOrderNo()); request.setOutTradeNo(order.getOrderNo()); request.setNotifyUrl(wechatConfig.getNotifyUrl()); request.setAmount(new Amount(order.getPayAmount().multiply(new BigDecimal(100)).intValue())); request.setPayer(new Payer(openid)); return wechatPayService.createPrepayOrder(request); } PostMapping(/pay/notify) public String handlePayNotify(RequestBody String notifyData) { try { // 验证签名 if (!wechatPayService.verifySignature(notifyData)) { return FAIL; } // 解析支付结果 PayNotifyResponse response JSON.parseObject(notifyData, PayNotifyResponse.class); if (SUCCESS.equals(response.getTradeState())) { // 更新订单状态为已支付 orderService.updateOrderPaid(response.getOutTradeNo(), response.getTransactionId(), response.getSuccessTime()); } return SUCCESS; } catch (Exception e) { log.error(处理支付回调异常, e); return FAIL; } } }4. 微信小程序前端开发要点原生微信小程序开发需要注意页面布局、API调用和性能优化。4.1 页面布局与样式适配微信小程序需要适配不同屏幕特别是顶部导航栏高度// app.js App({ onLaunch() { // 获取系统信息计算导航栏高度 const systemInfo wx.getSystemInfoSync() const statusBarHeight systemInfo.statusBarHeight const menuButtonInfo wx.getMenuButtonBoundingClientRect() const navBarHeight (menuButtonInfo.top - statusBarHeight) * 2 menuButtonInfo.height this.globalData { statusBarHeight, navBarHeight, screenWidth: systemInfo.screenWidth, screenHeight: systemInfo.screenHeight } } }) // 页面使用 Page({ data: { navBarHeight: 0 }, onLoad() { const app getApp() this.setData({ navBarHeight: app.globalData.navBarHeight }) } })/* 页面样式 */ .nav-bar { height: {{navBarHeight}}px; padding-top: {{statusBarHeight}}px; background: #07C160; color: white; } .content { margin-top: {{navBarHeight}}px; }4.2 文件上传实现农产品需要多图展示文件上传是常见需求// 选择图片 chooseImages() { wx.chooseImage({ count: 5, sizeType: [compressed], sourceType: [album, camera], success: (res) { this.uploadImages(res.tempFilePaths) } }) }, // 上传图片 uploadImages(tempFilePaths) { const uploadTasks tempFilePaths.map((filePath, index) { return new Promise((resolve, reject) { wx.uploadFile({ url: https://your-domain.com/api/upload, filePath: filePath, name: file, formData: { type: product }, success: (res) { const data JSON.parse(res.data) if (data.code 0) { resolve(data.data.url) } else { reject(new Error(data.message)) } }, fail: reject }) }) }) Promise.all(uploadTasks).then(urls { this.setData({ productImages: [...this.data.productImages, ...urls] }) }).catch(error { wx.showToast({ title: 上传失败, icon: none }) }) }4.3 数据缓存与状态管理小程序端需要合理使用缓存提升用户体验// utils/storage.js const storage { // 设置缓存带过期时间 set(key, data, expire 24 * 60 * 60 * 1000) { const item { data, expire: Date.now() expire } wx.setStorageSync(key, item) }, // 获取缓存 get(key) { const item wx.getStorageSync(key) if (!item) return null if (Date.now() item.expire) { wx.removeStorageSync(key) return null } return item.data }, // 清除用户相关缓存 clearUserData() { wx.removeStorageSync(token) wx.removeStorageSync(userInfo) wx.removeStorageSync(cartData) } } export default storage5. Vue3管理后台开发管理后台需要实现商品审核、订单管理、数据统计等功能。5.1 组合式API使用Vue3的组合式API更适合复杂业务逻辑的组织template div el-table :dataproducts v-loadingloading el-table-column propname label商品名称/el-table-column el-table-column propfarmerName label农户/el-table-column el-table-column propstatus label状态 template #defaultscope el-tag :typescope.row.status 1 ? success : info {{ scope.row.status 1 ? 上架 : 下架 }} /el-tag /template /el-table-column el-table-column label操作 template #defaultscope el-button clickhandleEdit(scope.row)编辑/el-button el-button clickhandleToggleStatus(scope.row) {{ scope.row.status 1 ? 下架 : 上架 }} /el-button /template /el-table-column /el-table /div /template script setup import { ref, onMounted } from vue import { ElMessage, ElMessageBox } from element-plus import { getProducts, updateProductStatus } from /api/product const loading ref(false) const products ref([]) // 加载商品列表 const loadProducts async () { loading.value true try { const response await getProducts() products.value response.data } catch (error) { ElMessage.error(加载失败) } finally { loading.value false } } // 切换商品状态 const handleToggleStatus async (product) { try { await ElMessageBox.confirm( 确定要${product.status 1 ? 下架 : 上架}该商品吗, 提示, { type: warning } ) await updateProductStatus(product.id, product.status 1 ? 0 : 1) ElMessage.success(操作成功) loadProducts() // 重新加载列表 } catch (error) { // 用户取消操作 } } onMounted(() { loadProducts() }) /script5.2 路由状态保持商品列表页到详情页的跳转需要保持查询状态// router/index.js import { createRouter, createWebHistory } from vue-router const routes [ { path: /products, name: ProductList, component: () import(/views/ProductList.vue), meta: { keepAlive: true } // 保持组件状态 }, { path: /products/:id, name: ProductDetail, component: () import(/views/ProductDetail.vue) } ] const router createRouter({ history: createWebHistory(), routes }) // 路由守卫中保存滚动位置 router.beforeEach((to, from, next) { if (from.meta.keepAlive) { from.meta.scrollTop document.documentElement.scrollTop || document.body.scrollTop } next() }) router.afterEach((to, from) { if (to.meta.keepAlive to.meta.scrollTop) { setTimeout(() { window.scrollTo(0, to.meta.scrollTop) }, 0) } })6. 部署与生产环境配置多端项目部署需要考虑前后端分离、域名配置和HTTPS要求。6.1 后端服务部署SpringBoot应用可以使用Docker容器化部署# Dockerfile FROM openjdk:17-jdk-slim # 设置时区 RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime # 创建应用目录 WORKDIR /app # 复制jar包 COPY target/farm-mall-backend-1.0.0.jar app.jar # 暴露端口 EXPOSE 8080 # 启动命令 ENTRYPOINT [java, -jar, app.jar, --spring.profiles.activeprod]使用Docker Compose编排整个服务栈# docker-compose.yml version: 3.8 services: backend: build: ./farm-mall-backend ports: - 8080:8080 environment: - SPRING_PROFILES_ACTIVEprod - SPRING_DATASOURCE_URLjdbc:mysql://mysql:3306/farm_mall - SPRING_REDIS_HOSTredis depends_on: - mysql - redis mysql: image: mysql:8.0 environment: MYSQL_ROOT_PASSWORD: your_secure_password MYSQL_DATABASE: farm_mall volumes: - mysql_data:/var/lib/mysql ports: - 3306:3306 redis: image: redis:6.2-alpine ports: - 6379:6379 volumes: mysql_data:6.2 微信小程序部署注意事项小程序上线前需要完成服务器域名配置request合法域名后端API域名uploadFile合法域名文件上传域名downloadFile合法域名文件下载域名所有域名必须支持HTTPS且完成备案。6.3 生产环境安全检查清单检查项要求检查方式数据库密码强密码非默认确认密码复杂度API密钥环境变量管理不写代码中检查配置读取方式SSL证书有效且覆盖所有域名使用SSL检测工具日志输出不包含敏感信息检查日志文件内容依赖漏洞无已知安全漏洞使用漏洞扫描工具权限控制接口有权限验证测试未授权访问7. 常见问题排查与优化建议在实际开发中会遇到各种问题提前了解排查思路能节省大量时间。7.1 微信小程序常见问题问题1上传文件报错[wxapplib] backgroundfetch privacy fail这个错误通常是因为文件上传域名未配置或HT证书问题检查小程序后台「开发」-「开发设置」-「服务器域名」配置确认上传域名已备案且支持HTTPS检查SSL证书是否有效且域名匹配问题2页面布局错乱特别是导航栏区域使用wx.getMenuButtonBoundingClientRect()获取正确的按钮位置考虑不同机型的状态栏高度差异在app.onLaunch中计算并存储导航栏高度问题3微信登录失败检查appid和secret是否正确确认网络请求域名已配置查看微信接口返回的具体错误码7.2 SpringBoot后端性能优化数据库连接池配置spring: datasource: hikari: maximum-pool-size: 20 minimum-idle: 5 connection-timeout: 30000 idle-timeout: 600000 max-lifetime: 1800000Redis缓存策略Configuration EnableCaching public class CacheConfig { Bean public RedisCacheManager cacheManager(RedisConnectionFactory factory) { RedisCacheConfiguration config RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofMinutes(30)) // 默认缓存30分钟 .disableCachingNullValues(); return RedisCacheManager.builder(factory) .cacheDefaults(config) .build(); } }API响应优化// 使用DTO避免返回完整实体 Data public class ProductDTO { private Long id; private String name; private BigDecimal price; private String image; // 只返回前端需要的字段 } // 分页查询优化 public PageResultProductDTO getProducts(int page, int size, String keyword) { PageHelper.startPage(page, size); ListProduct products productMapper.selectByKeyword(keyword); ListProductDTO dtos products.stream() .map(this::convertToDTO) .collect(Collectors.toList()); return new PageResult(dtos, ((Page) products).getTotal()); }7.3 Vue3管理后台体验优化列表页查询状态保持// 使用Vuex或Pinia管理查询条件 import { defineStore } from pinia export const useProductStore defineStore(product, { state: () ({ queryParams: { keyword: , category: , status: , page: 1, size: 20 } }), actions: { setQueryParams(params) { this.queryParams { ...this.queryParams, ...params } }, // 从详情页返回时恢复查询条件 restoreQueryParams() { return this.queryParams } } })表格性能优化template el-table :dataproducts v-loadingloading :row-keyrow row.id sort-changehandleSortChange filter-changehandleFilterChange !-- 使用固定列和虚拟滚动优化大数据量 -- /el-table /template助农扶贫商城项目涉及的技术栈较广建议按模块分阶段实现。先从后端基础功能和微信小程序用户端开始确保核心购物流程跑通再逐步加入管理后台和AI智能功能。每个阶段都要充分测试特别是支付流程和订单状态流转这是电商项目的关键质量点。实际部署时可以先从测试环境开始逐步验证各项功能在生产环境的稳定性。特别是微信支付和文件上传这类依赖外部服务的功能需要完整的测试用例覆盖。
返回列表