You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:基于Gradle实现Reactjs与Spring-mvc的整合方案

Gradle 整合 React + Spring MVC 完整方案

Hey there, I’ve worked through this exact scenario a few times—let’s get your Gradle-based setup up and running smoothly, since most guides do lean hard on Maven. Here’s a step-by-step approach that’s proven to work:

1. 项目结构规划

First, let’s lay out a clean structure that keeps backend and frontend code separated but easy to integrate:

your-project/
├── src/
│   ├── main/
│   │   ├── java/          # Spring MVC 后端代码
│   │   ├── resources/
│   │   │   ├── static/    # React 构建产物会输出到这里
│   │   │   └── templates/ # (可选)若使用 Thymeleaf,纯 React SPA 无需此目录
│   │   └── frontend/      # React 项目目录
│   └── test/              # 后端测试代码
├── build.gradle
└── settings.gradle

2. Gradle 核心配置

This is the most critical part—we’ll use Gradle’s Node.js plugin to handle React’s build process and wire it into the Spring build lifecycle.

Add the necessary plugins and dependencies to your build.gradle:

plugins {
    id 'java'
    id 'org.springframework.boot' version '3.2.0'
    id 'io.spring.dependency-management' version '1.1.4'
    id 'com.github.node-gradle.node' version '7.0.0' // 用于构建 React
}

group = 'com.yourcompany'
version = '0.0.1-SNAPSHOT'

java {
    sourceCompatibility = '17'
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    // 添加你需要的其他 Spring 依赖(如 data-jpa、security 等)
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

// 配置 Node.js 插件
node {
    download = true // 若本地无 Node.js,自动下载
    version = '20.10.0' // 使用与 React 兼容的稳定 Node 版本
    nodeProjectDir = file('src/main/frontend') // 指定 React 项目根目录
}

// 自定义任务:构建 React 并将静态文件复制到 Spring 的 static 目录
task copyReactBuild(type: Copy) {
    dependsOn 'npm_run_build'
    from "${nodeProjectDir}/build" // React 构建输出目录
    into "${projectDir}/src/main/resources/static" // Spring 静态资源目录
}

// 将 React 构建绑定到 Gradle 构建生命周期
processResources.dependsOn copyReactBuild

test {
    useJUnitPlatform()
}

3. React 项目设置

Now set up your React project in src/main/frontend:

  1. 打开终端,进入 src/main/frontend 目录,执行:
    npx create-react-app .
    
  2. (可选)修改 package.json 中的构建命令,让产物直接输出到 Spring 静态目录(不过用 Gradle 复制任务更兼容跨平台):
    {
      "name": "frontend",
      "version": "0.1.0",
      "private": true,
      "scripts": {
        "start": "react-scripts start",
        "build": "react-scripts build",
        "test": "react-scripts test",
        "eject": "react-scripts eject"
      },
      // ... 其余 package.json 内容
    }
    

4. Spring MVC 配置

4.1 静态资源访问

如果使用 Spring Boot,它会自动从 src/main/resources/static 提供静态资源,构建后的 React 应用可通过根路径(如 http://localhost:8080)访问。

4.2 处理 React SPA 路由

对于使用 React Router 的单页应用,需要配置 Spring 将所有非 API 请求转发到 index.html:
创建如下控制器:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class ForwardController {

    // 将所有非 API 的 GET 请求转发到 React 的 index.html
    @GetMapping(value = "/**/{path:[^.]*}")
    public String forwardToReact() {
        return "forward:/index.html";
    }
}

4.3 开发环境跨域处理

开发时,若 React 运行在 localhost:3000,Spring 运行在 localhost:8080,需开启 CORS:

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 WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOrigins("http://localhost:3000")
                .allowedMethods("GET", "POST", "PUT", "DELETE");
    }
}

5. 构建与运行

5.1 生产构建

执行以下命令,同时构建 Spring 后端和 React 前端,并打包为单个 JAR:

./gradlew clean build

运行打包好的 JAR:

java -jar build/libs/your-project-0.0.1-SNAPSHOT.jar

5.2 开发模式

为了提升开发效率:

  1. 启动 Spring Boot:
    ./gradlew bootRun
    
  2. 打开另一个终端,进入 src/main/frontend 启动 React 开发服务器:
    npm start
    
    React 应用将运行在 localhost:3000,可直接调用 Spring API(如 http://localhost:8080/api/...)

关键注意事项

  • Node.js 版本: 确保 Gradle 配置中的 Node 版本与 React 项目兼容(可查看 package.json 的 engines 字段)。
  • 热重载: 若需后端热重载,添加依赖 implementation 'org.springframework.boot:spring-boot-devtools'。
  • 构建顺序: Gradle 配置确保 React 先完成构建,再让 Spring 处理资源,保证最终 JAR 中的静态文件是最新的。

内容的提问来源于stack exchange,提问作者Akorful Nicholas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 18:42:31