从 spring-boot 应用程序提供 Angular 前端的最简单方法是拥有一个多模块项目。然后自动化构建过程以在maven clean install 本身期间将 ui 模块中的 dist 文件夹复制到服务模块中。这样,您可以拥有一个也为 angular 服务的可执行 jar。例如,考虑以下项目结构:
SampleMultiModuleProject
|__SampleMultiModuleService
|__SampleMultiModuleUI
在这种情况下,您将拥有三个不同的 pom 文件,如下所示。
SampleMultiModuleProject main pom.xml :(所有主要依赖项都存在)
<modules>
<module>SampleMultiModuleUI</module>
<module>SampleMultiModuleService</module>
</modules>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/>
</parent>
//在此处添加其余的依赖项。
SampleMultiModuleService service pom.xml : (用于服务模块并添加springboot maven插件使其可以与嵌入式tomcat一起执行,并添加服务模块中需要的其他依赖项,例如lombok)
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
最后配置 ui 模块来构建 angular 像 SampleMultiModuleUI pom.xml :
<build>
<plugins>
<plugin>
<groupId>com.github.eirslett</groupId>
<artifactId>frontend-maven-plugin</artifactId>
<version>1.9.1</version>
<configuration>
<workingDirectory>./</workingDirectory>
<nodeVersion>v13.3.0</nodeVersion>
<npmVersion>6.13.1</npmVersion>
<nodeDownloadRoot>http://nodejs.org/dist/</nodeDownloadRoot>
<npmDownloadRoot>http://registry.npmjs.org/npm/-/</npmDownloadRoot>
<installDirectory>./</installDirectory>
<npmInheritsProxyConfigFromMaven>false</npmInheritsProxyConfigFromMaven>
</configuration>
<executions>
<execution>
<id>install node and npm</id>
<goals>
<goal>install-node-and-npm</goal>
</goals>
<phase>generate-resources</phase>
</execution>
<execution>
<id>npm install</id>
<goals>
<goal>npm</goal>
</goals>
<phase>generate-resources</phase>
<configuration>
<arguments>install</arguments>
</configuration>
</execution>
<execution>
<id>npm run-script build-prod</id>
<phase>prepare-package</phase>
<goals>
<goal>npm</goal>
</goals>
<configuration>
<arguments>run-script build</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
所以当你执行 maven clean install 时会发生什么,它会触发 ui 模块的构建,然后使用前端构建器安装一个本地 npm,该 npm 运行参数中指定的命令。默认情况下,您的 Angular 应用程序中的 package.json 文件将包含以下内容:
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build --prod",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e",
"stats": "webpack-bundle-analyzer dist/stats.json"
},
所以你实际上是通过这个过程调用这个ng build --prod。同样在angular.json中将output path设置为你项目中服务模块下的资源文件夹,这样资产就会在那里创建。
"newProjectRoot": "projects",
"projects": {
"SampleMultiModuleUI": {
"projectType": "application",
"schematics": {},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "../SampleMultiModuleService/src/main/resources/static",
//rest of the config