> 技术文档 > 10分钟搭建脚手架:Spring Boot 3.2 + Vue3 前后端分离模板

10分钟搭建脚手架:Spring Boot 3.2 + Vue3 前后端分离模板


10分钟搭建脚手架:Spring Boot 3.2 + Vue3 前后端分离模板

  • 一、项目结构设计
  • 二、后端搭建(Spring Boot 3.2)
    • 1. 快速初始化(使用 Spring Initializr)
    • 2. 核心配置
      • application.yml
      • 跨域配置 CorsConfig.java
    • 3. 安全配置
      • SecurityConfig.java
    • 4. JWT认证模块
      • JwtUtils.java
  • 三、前端搭建(Vue3 + Vite)
    • 1. 创建Vue项目
    • 2. 安装必要依赖
    • 3. 项目结构优化
    • 4. 核心配置
      • axios 封装 (api/index.ts)
      • 路由配置 (router/index.ts)
  • 四、前后端联调配置
    • 1. 开发环境代理 (Vite)
    • 2. 生产环境整合
  • 五、一键启动脚本
    • start-dev.sh (开发环境)
    • build-prod.sh (生产构建)
  • 六、Docker 容器化
    • Dockerfile (后端)
    • docker-compose.yml
  • 七、模板功能清单
  • 八、性能优化配置
    • 前端优化 (Vite)
    • 后端优化
  • 九、扩展功能集成
    • 1. 代码生成器
    • 2. 监控端点
  • 十、使用说明

一、项目结构设计

my-project/├── backend/ # Spring Boot 3.2 后端├── frontend/ # Vue3 前端└── docker-compose.yml # 容器化部署

二、后端搭建(Spring Boot 3.2)

1. 快速初始化(使用 Spring Initializr)

  • 依赖选择:
    • Spring Web
    • Spring Data JPA
    • Lombok
    • Spring Security
    • MySQL Driver
    • Spring Boot DevTools

2. 核心配置

application.yml

server: port: 8080 servlet: context-path: /apispring: datasource: url: jdbc:mysql://localhost:3306/app_db?useSSL=false username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver jpa: hibernate: ddl-auto: update show-sql: true properties: hibernate.format_sql: true security: oauth2: resourceserver: jwt: issuer-uri: http://localhost:8080

跨域配置 CorsConfig.java

@Configurationpublic class CorsConfig { @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOriginPattern(\"*\"); config.addAllowedHeader(\"*\"); config.addAllowedMethod(\"*\"); source.registerCorsConfiguration(\"/**\", config); return new CorsFilter(source); }}

3. 安全配置

SecurityConfig.java

@Configuration@EnableWebSecuritypublic class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .csrf().disable() .authorizeHttpRequests(auth -> auth .requestMatchers(\"/api/auth/**\").permitAll() .anyRequest().authenticated() ) .sessionManagement(session -> session .sessionCreationPolicy(SessionCreationPolicy.STATELESS) ); return http.build(); }}

4. JWT认证模块

JwtUtils.java

public class JwtUtils { private static final String SECRET_KEY = \"mySecretKey\"; private static final long EXPIRATION_TIME = 86400000; // 24小时 public static String generateToken(UserDetails userDetails) { return Jwts.builder() .setSubject(userDetails.getUsername()) .setIssuedAt(new Date()) .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME)) .signWith(SignatureAlgorithm.HS256, SECRET_KEY) .compact(); } public static String extractUsername(String token) { return Jwts.parser() .setSigningKey(SECRET_KEY) .parseClaimsJws(token) .getBody() .getSubject(); }}

三、前端搭建(Vue3 + Vite)

1. 创建Vue项目

npm create vite@latest frontend -- --template vue-tscd frontendnpm install

2. 安装必要依赖

npm install axios vue-router@4 pinia @element-plus/icons-vuenpm install -D sass

3. 项目结构优化

src/├── api/  # API请求封装├── assets/ # 静态资源├── components/ # 通用组件├── router/ # 路由配置├── store/ # 状态管理├── views/ # 页面组件├── utils/ # 工具函数└── App.vue

4. 核心配置

axios 封装 (api/index.ts)

import axios from \'axios\';const api = axios.create({ baseURL: import.meta.env.DEV ? \'http://localhost:8080/api\' : \'/api\', timeout: 10000,});// 请求拦截器api.interceptors.request.use(config => { const token = localStorage.getItem(\'token\'); if (token) { config.headers.Authorization = `Bearer ${token}`; } return config;});// 响应拦截器api.interceptors.response.use( response => response.data, error => { if (error.response?.status === 401) { localStorage.removeItem(\'token\'); window.location.href = \'/login\'; } return Promise.reject(error); });export default api;

路由配置 (router/index.ts)

import { createRouter, createWebHistory } from \'vue-router\';const routes = [ { path: \'/\', name: \'Home\', component: () => import(\'@/views/HomeView.vue\'), meta: { requiresAuth: true } }, { path: \'/login\', name: \'Login\', component: () => import(\'@/views/LoginView.vue\') }];const router = createRouter({ history: createWebHistory(), routes});router.beforeEach((to, from, next) => { const token = localStorage.getItem(\'token\'); if (to.meta.requiresAuth && !token) { next(\'/login\'); } else { next(); }});export default router;

四、前后端联调配置

1. 开发环境代理 (Vite)

// vite.config.jsexport default defineConfig({ plugins: [vue()], server: { proxy: { \'/api\': { target: \'http://localhost:8080\', changeOrigin: true, rewrite: path => path.replace(/^\\/api/, \'\') } } }})

2. 生产环境整合

// Spring Boot 配置 (WebMvcConfig.java)@Configurationpublic class WebMvcConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler(\"/**\") .addResourceLocations(\"classpath:/static/\") .resourceChain(true) .addResolver(new PathResourceResolver() { @Override protected Resource getResource(String resourcePath,  Resource location) throws IOException {  Resource requestedResource = location.createRelative(resourcePath);  return requestedResource.exists() && requestedResource.isReadable() ? requestedResource : new ClassPathResource(\"/static/index.html\"); } }); }}

五、一键启动脚本

start-dev.sh (开发环境)

#!/bin/bash# 启动后端cd backend && ./mvnw spring-boot:run &# 启动前端cd frontend && npm run dev

build-prod.sh (生产构建)

#!/bin/bash# 构建前端cd frontendnpm run build# 复制前端构建文件到后端rm -rf ../backend/src/main/resources/static/*cp -r dist/* ../backend/src/main/resources/static/# 构建后端JARcd ../backend./mvnw clean package -DskipTests

六、Docker 容器化

Dockerfile (后端)

FROM openjdk:17-jdk-slimARG JAR_FILE=target/*.jarCOPY ${JAR_FILE} app.jarENTRYPOINT [\"java\",\"-jar\",\"/app.jar\"]

docker-compose.yml

version: \'3.8\'services: backend: build: ./backend ports: - \"8080:8080\" environment: SPRING_DATASOURCE_URL: jdbc:mysql://db:3306/app_db SPRING_DATASOURCE_USERNAME: root SPRING_DATASOURCE_PASSWORD: root depends_on: db: condition: service_healthy frontend: image: nginx:alpine ports: - \"80:80\" volumes: - ./frontend/dist:/usr/share/nginx/html depends_on: - backend db: image: mysql:8.0 environment: MYSQL_ROOT_PASSWORD: root MYSQL_DATABASE: app_db volumes: - mysql-data:/var/lib/mysql healthcheck: test: [\"CMD\", \"mysqladmin\", \"ping\", \"-h\", \"localhost\"] interval: 5s timeout: 10s retries: 5volumes: mysql-data:

七、模板功能清单

  1. 后端功能:
    • JWT认证
    • 统一异常处理
    • 数据验证
    • 分页查询
    • 文件上传
    • API文档 (SpringDoc OpenAPI)
  2. 前端功能:
    • 响应式布局
    • 路由守卫
    • 状态管理
    • 主题切换
    • 国际化
    • 权限控制

八、性能优化配置

前端优化 (Vite)

// vite.config.jsexport default defineConfig({ build: { rollupOptions: { output: { manualChunks(id) { if (id.includes(\'node_modules\')) { return \'vendor\'; } } } } }})

后端优化

# application.ymlspring: jpa: properties: hibernate: jdbc: batch_size: 50 fetch_size: 100 order_inserts: true order_updates: true

九、扩展功能集成

1. 代码生成器

# 安装MyBatis Plus代码生成器<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.5.3</version></dependency>

2. 监控端点

management: endpoints: web: exposure: include: health,info,metrics,prometheus endpoint: health: show-details: always

十、使用说明

  1. 开发模式:
./start-dev.sh
  1. 生产构建:
./build-prod.sh
  1. 容器部署:
docker-compose up -d --build

该模板已集成企业级开发所需的核心功能,10分钟内即可启动开发,适合作为微服务架构的基础模板。