在 AIGC(生成式 AI) 时代,开发者不仅需要快速完成项目的原型开发,还要高效搭建一个灵活、可扩展的全栈开发环境。今天我们将带你一步步搭建一个 前后端分离 的全栈项目,后端使用 Spring Boot 3,前端使用 Vue 3。通过结合 IntelliJ IDEA 和 ChatGPT,你将能轻松完成一个标准的全栈开发环境,从而实现快速上线和开发。即便是初学者,跟随我们的教程,也能成功创建并运行一个完整的 Spring Boot + Vue 3 项目!让我们开始吧!
- [IntelliJ IDEA](https://www.jetbrains.com/idea/)(建议使用 Ultimate 版,功能更强大,支持更多的后端框架和前端功能)
- [Node.js](https://nodejs.org/)(推荐 LTS 版本)
- [JDK 17](https://www.oracle.com/java/technologies/javase/jdk17-archive-downloads.html)(Spring Boot 3.x 推荐使用 JDK 17 以上版本)
- [Maven](https://maven.apache.org/) 或 Gradle(Spring Boot 项目的构建工具)
- 操作系统:Windows/Mac/Linux
- 最低硬件配置:8GB 内存,500GB 硬盘(推荐 SSD)
- 配置国内镜像(如 Maven 阿里云镜像、NPM 淘宝镜像)以提高依赖下载速度。
首先打开 IntelliJ IDEA,并创建一个新的 Spring Boot 项目。
- **Spring Web**:用于创建 RESTful API。
- **Spring Data JPA**:用于与数据库交互。
- **Spring Security**:用于实现身份认证和权限控制。
- **MySQL Driver**:连接 MySQL 数据库。
然后点击 Next,选择项目保存路径,点击 Finish 完成创建。
联网等待jar依赖下载完成即可开始编码~
application.yml
文件接下来,我们需要配置 Spring Boot 项目的数据库连接信息。进入项目目录下的 src/main/resources/application.yml
文件,添加以下配置:
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
username: root
password: root
jpa:
hibernate:
ddl-auto: update
show-sql: true
sql:
init:
mode: always
mydb
数据库。ddl-auto: update
意味着 Spring Boot 会自动更新数据库表结构。接下来,我们会创建一个简单的 RESTful API 来管理用户。首先,创建一个 UserController 类。
在 src/main/java/com/example/springbootvue3demo/controller
目录下创建 UserController.java
文件:
package com.example.springbootvue3demo.controller;
import com.example.springbootvue3demo.model.User;
import com.example.springbootvue3demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/register")
public String registerUser(@RequestBody User user) {
userService.save(user);
return "User registered successfully!";
}
@PostMapping("/login")
public String loginUser(@RequestBody User user) {
return userService.login(user);
}
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
return userService.findById(id);
}
}
接着,创建 User 实体类(User.java
):
package com.example.springbootvue3demo.model;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class User {
@Id
private Long id;
private String username;
private String password;
// Getters and setters
}
最后,创建 UserService 服务类,负责处理用户数据:
package com.example.springbootvue3demo.service;
import com.example.springbootvue3demo.model.User;
import org.springframework.stereotype.Service;
@Service
public class UserService {
// Simulating database operations for demo purposes
public void save(User user) {
// Logic to save user to the database
}
public String login(User user) {
// Simulate login logic
return "Login successful for " + user.getUsername();
}
public User findById(Long id) {
// Simulate fetching user from the database
return new User();
}
}
通过命令行创建一个新的 Vue 3 项目:
npm init vue@latest
cd vue3-project
npm install
选择 Vue 3,并添加 Vue Router 和 Pinia 作为状态管理工具。
进入 src
文件夹,创建以下目录结构:
在项目根目录下运行以下命令安装所需的依赖:
npm install axios vue-router@4 pinia
src/router/index.js
文件中:import { createRouter, createWebHistory } from 'vue-router';
const routes = [
{ path: '/', component: () => import('../views/Home.vue') },
{ path: '/login', component: () => import('../views/Login.vue') },
];
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;
src/store/index.js
文件中:import { defineStore } from 'pinia';
export const useUserStore = defineStore('user', {
state: () => ({
user: null,
}),
actions: {
setUser(user) {
this.user = user;
},
},
});
在 src/views/Login.vue
中,使用 Vue 3 语法创建登录表单:
<template>
<form @submit.prevent="login">
<input v-model="username" placeholder="用户名" />
<input v-model="password" type="password" placeholder="密码" />
<button type="submit">登录</button>
</form>
</template>
<script setup>
import { ref } from 'vue';
import axios from 'axios';
const username = ref('');
const password = ref('');
const login = async () => {
const response = await axios.post('http://localhost:8080/api/users/login', {
username: username.value,
password: password.value,
});
console.log(response.data);
};
</script>
在项目根目录下,运行以下命令启动 Vue 前端:
npm run dev
实现前后端分离的核心是确保后端 API 能够与前端正常通信,以下是详细的联调过程。
由于前端和后端运行在不同的端口(如前端运行在 http://localhost:3000
,后端运行在 http://localhost:8080
),浏览器会限制跨域请求。因此需要在后端配置 CORS(跨域资源共享)。
在后端创建一个配置类 WebMvcConfig
,启用跨域支持:
package com.example.springbootvue3demo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 允许所有路径
.allowedOrigins("http://localhost:3000") // 允许的前端地址
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的请求方法
.allowedHeaders("*") // 允许的请求头
.allowCredentials(true); // 允许携带认证信息(如 Cookies)
}
}
提示:
allowedOrigins
的地址可以换成部署后前端项目的实际地址。
执行以下命令启动 Spring Boot 后端服务:
mvn spring-boot:run
http://localhost:8080
启动。http://localhost:8080/api/users
,确保接口正常运行。在前端项目中,使用 Axios 发送请求时需要设置后端的基础 URL 和跨域配置。以下是具体步骤:
安装 Axios
确保 Axios 已安装:
npm install axios
配置 Axios 基础设置
在 src/utils/axios.js
文件中配置 Axios 实例:
import axios from 'axios';
const apiClient = axios.create({
baseURL: 'http://localhost:8080/api', // 后端 API 的基础路径
timeout: 5000, // 请求超时时间
headers: {
'Content-Type': 'application/json',
},
});
export default apiClient;
在 Vue 项目中使用 Axios
修改登录组件中的代码,确保与后端 API 通信正常:
<template>
<form @submit.prevent="login">
<input v-model="username" placeholder="用户名" />
<input v-model="password" type="password" placeholder="密码" />
<button type="submit">登录</button>
</form>
</template>
<script setup>
import { ref } from 'vue';
import apiClient from '../utils/axios';
const username = ref('');
const password = ref('');
const login = async () => {
try {
const response = await apiClient.post('/users/login', {
username: username.value,
password: password.value,
});
console.log(response.data);
alert('登录成功');
} catch (error) {
console.error(error);
alert('登录失败');
}
};
</script>
在前端项目的根目录下,执行以下命令启动 Vue 前端:
npm run dev
前端默认运行在 http://localhost:3000
,打开浏览器访问此地址。
- 在浏览器中打开前端页面,填写用户名和密码,点击“登录”按钮。
- 检查后端日志或前端控制台,确认请求是否成功,返回的数据是否正确。
- **CORS 错误**:检查后端 CORS 配置是否正确,特别是 `allowedOrigins` 的值。
- **Axios 网络请求错误**:确保 Axios 的 `baseURL` 与后端实际地址一致。
在联调完成后,为了避免后续的接口版本升级对前端造成影响,建议在 API 路径中加入版本号。例如:
后端 API 路径改为:http://localhost:8080/api/v1/users
在前端 Axios 配置中同步更新基础路径:
const apiClient = axios.create({
baseURL: 'http://localhost:8080/api/v1', // 添加版本号
timeout: 5000,
headers: {
'Content-Type': 'application/json',
},
});
这样可以在后端版本更新时,新版本的接口路径可以通过 /api/v2
等路径区分,而不影响旧版本的前端项目。
通过以上步骤,你可以成功实现 Spring Boot 3 后端 与 Vue 3 前端 的无缝联调。🎉 现在,你的全栈项目已经可以正常运行并完成基本的功能开发了!
在搭建过程中,ChatGPT 是你的得力助手。以下是 ChatGPT 在全栈项目开发中能提供的帮助:
通过提示,ChatGPT 可以快速生成符合需求的代码片段。例如,你可以让 ChatGPT 帮你生成用户注册接口或 Vue 的表单组件。
示例提示:
“生成一个 Spring Boot 的登录 API,包括接收用户名和密码,并返回一个 JSON 响应。”
生成代码如下:
package com.example.demo.controller;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/api/auth")
public class LoginController {
@PostMapping("/login")
public Map<String, Object> login(@RequestParam String username, @RequestParam String password) {
Map<String, Object> response = new HashMap<>();
// 模拟用户验证逻辑
if ("admin".equals(username) && "password123".equals(password)) {
response.put("status", "success");
response.put("message", "登录成功!");
response.put("token", "fake-jwt-token"); // 生成的 token 示例
} else {
response.put("status", "error");
response.put("message", "用户名或密码错误!");
}
return response;
}
}
如果你在运行中遇到错误,比如 CORS
问题、NullPointerException
等,ChatGPT 可以帮助你快速排查并提供修复方法。
对于不熟悉的框架或技术栈,ChatGPT 可以快速为你总结概念并提供实际代码示例。比如,它可以告诉你 Vue 3 和 Vue 2 的主要差异,并帮助你升级代码。
为进一步提高开发效率和运行性能,可以采取以下措施:
Dockerfile
和 docker-compose.yml
,快速搭建生产环境。示例:后端 Dockerfile
FROM openjdk:17-jdk-alpine
VOLUME /tmp
ARG JAR_FILE=target/spring-boot-vue3-demo-0.0.1-SNAPSHOT.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java", "-jar", "/app.jar"]
示例:前端 Dockerfile
FROM node:16
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["npm", "run", "dev"]
项目成功运行后,你可以继续扩展以下功能:
解决方案:
确保 MySQL 服务已启动,并检查 application.yml
中的数据库配置。
测试数据库连接是否正常:
mysql -u root -p -h localhost -P 3306
解决方案:
8080
)。解决方案:
npm config set registry https://registry.npm.taobao.org
或直接使用 cnpm:
npm install -g cnpm --registry=https://registry.npmmirror.com
在 AIGC 时代,开发者需要快速适应技术更新,以更高效的方式完成复杂项目。通过本文的详细步骤,相信你已经学会如何快速搭建一个 Spring Boot 3 + Vue 3 的全栈开发环境,并将前后端分离架构的优势应用到实际项目中。
猫头虎技术团队 鼓励你不断探索与实践,让技术为你的项目增值!
💡 想了解更多开发实战经验?立即关注公众号「猫头虎技术团队」,与我们一起玩转技术前沿! 🚀