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

Spring Boot与Angular整合:无需单独启动Angular服务器的部署问询

完全可以实现整合运行与部署

开发阶段:整合Angular开发服务与Spring Boot

开发时无需单独维护两个服务进程,通过代理转发就能让前端请求自动指向Spring Boot后端:

  • 在Angular项目根目录创建proxy.conf.json,配置API请求转发规则:
{
  "/api/*": {
    "target": "http://localhost:8080",
    "secure": false,
    "logLevel": "info"
  }
}
  • 启动Angular时指定代理配置:ng serve --proxy-config proxy.conf.json
  • 此时前端所有以/api开头的请求都会自动转发到Spring Boot,同时保留Angular热重载的开发便利。

生产阶段:打包Angular嵌入Spring Boot部署

这是最常用的生产部署方案,只需启动Spring Boot一个服务即可运行整个应用:

  1. 打包Angular项目:在Angular根目录执行ng build --configuration production(旧版用ng build --prod),生成的静态文件会输出到dist/[你的项目名]目录
  2. 将dist/[你的项目名]下的所有文件,复制到Spring Boot项目的src/main/resources/static目录(无此目录则新建)
  3. 启动Spring Boot应用,访问http://localhost:8080即可直接加载Angular前端,API请求无需跨域配置
  4. 解决Angular路由刷新404问题:
    • 若用Hash路由:在Angular的AppRoutingModule中设置useHash: true,无需后端改动
    • 若用Path路由:在Spring Boot添加路由转发控制器,将非API请求导向index.html:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class SpaForwardController {
    @RequestMapping(value = "/**/{path:[^.]*}")
    public String forwardToIndex() {
        return "forward:/index.html";
    }
}

补充提示

  • 开发阶段若想直接通过Spring Boot访问前端,可先打包Angular再放入static目录,但会失去Angular热重载功能,仅适合快速验证整合效果
  • 生产环境可在Spring Boot的application.properties中配置静态资源缓存策略优化性能:
spring.web.resources.cache.cachecontrol.max-age=365d

内容的提问来源于stack exchange,提问作者Omkar Likhe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 16:48:15