一、背景
.NET體系下通常采用服務端渲染(如Razor Pages)或直接包含前端資源,而Java Spring Boot項目雖支持靜態資源打包,但Vue CLI工程需要獨立的構建流程。主管要求將編譯后的Vue工程直接嵌入JAR包中方便維護,本人不推薦這樣,原因有三:
- 第一、Vue CLI需要
npm run build
生成dist
,而Java項目通過Maven/Gradle打包,二者生命周期不同步;其次前端每次修改需重新構建并復制到resources/static
,破壞了前端熱更新優勢 - 第二、前端每次修改需重新構建并復制到
resources/static
,破壞了前端熱更新優勢。 - 第三、強制Java開發者處理前端構建,違背前后端分離架構原則。
獨立部署前端,通過Nginx反向代理解決跨域,保持技術棧自治性,才是正途。
二、集成過程
項目采用RuoYi前后端分離框架搭建,版本為3.8.9。將ruoyi-ui前端工程編譯打包后的dist目錄集成到Jar包中,主要分為前端和后端兩部分工作,話不多說,直接開干。
1.后端工程修改
后端工程的修改主要涉及三個地方:第一個是添加模版引擎的依賴并配置,第二個是靜態資源注冊映射;第三是鑒權攔截器放行靜態資源的訪問。
- 添加模版引擎依賴主要是為了支持渲染dist目錄的前端資源,需要引用與springboot版本匹配的依賴,如下:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>
# thymeleaf配置 spring:thymeleaf:prefix: classpath:/dist/mode: HTMLencoding: UTF-8cache: false
- 修改ResourcesConfig類,注冊靜態資源(registry.addResourceHandler("/static/**").addResourceLocations("classpath:/dist/static/"))和添加視圖控制器(
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/index").setViewName("index.html");
registry.addViewController("/").setViewName("index.html");
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
}),完整代碼如下:package com.book.framework.config;import com.book.common.config.RuoYiConfig; import com.book.common.constant.Constants; import com.book.framework.interceptor.RepeatSubmitInterceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean;