部署Spring Boot+React JAR到AWS Elastic Beanstalk遇Thymeleaf模板错误
解决Spring Boot + React打包JAR部署到Elastic Beanstalk的Thymeleaf模板找不到问题
问题根源
你配置的spring.thymeleaf.prefix=file:./target/classes/static/是本地文件系统路径,但Elastic Beanstalk运行的是打包后的JAR包,JAR内部的资源无法通过file:协议访问,必须使用classpath:前缀读取JAR内的资源。
具体修复步骤
1. 修正Thymeleaf前缀配置
修改application.properties中的Thymeleaf前缀配置:
# 替换原有的file:路径 spring.thymeleaf.prefix=classpath:/static/ spring.thymeleaf.suffix=.html
classpath:/static/会直接指向JAR包内/classes/static/目录,不管是本地运行JAR还是云端部署都能正确访问React构建后的index.html。
2. 清理冗余文件
删除src/main/resources/templates/下的空白index.html,避免Thymeleaf优先加载这个空白文件,确保加载的是static/目录下React生成的index.html。
3. 确认ErrorController的视图映射
保持你的ErrorController代码不变即可,Thymeleaf会根据新前缀找到static/index.html:
@RequestMapping(value ="/error") public ModelAndView mav(){ ModelAndView mav=new ModelAndView("index"); return mav; }
4. 验证打包与本地运行一致性
- 执行Maven打包命令:
mvn clean package - 本地用JAR方式启动项目:
java -jar target/your-app-name.jar,访问http://localhost:9001/home和http://localhost:9001/error确认正常,确保和云端运行环境一致。
5. 确认Maven资源复制配置
确保pom.xml中已配置将React构建产物复制到static目录的插件,示例配置如下:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>3.3.0</version> <executions> <execution> <id>copy-react-build</id> <phase>process-resources</phase> <goals> <goal>copy-resources</goal> </goals> <configuration> <outputDirectory>${project.build.outputDirectory}/static</outputDirectory> <resources> <resource> <!-- 替换为你的React项目构建目录,比如../react-app/build --> <directory>../react-app/build</directory> <filtering>false</filtering> </resource> </resources> </configuration> </execution> </executions> </plugin>
内容的提问来源于stack exchange,提问作者Nid
相关产品推荐
相关产品推荐

