如果使用的是 SpringBoot 多模块的项目,在发布的时候可能遇到各种各样的问题。本文归纳了以下 8 个原则和发布时经常出现的 4 个问题的解决方案,掌握了这些原则和解决方案,几乎可以解决绝大数 SpringBoot 发布问题。
比如,以下项目目录:
如果要发布
api 就直接在它的模块上打包,而不是在父模块上打包。
公共模块,比如
common 和
model 需要设置
packaging 为
jar 格式,在
pom.xml 配置:
<packaging>jar</packaging>
在发布的模块
pom.xml 中设置:
<packaging>war</packaging>
在发布的模块
pom.xml 中设置:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope></dependency>
当设置
scope=provided 时,此 jar 包不会出现在发布的项目中,从而就排除了内置的 tomcat。
此步骤相当于告诉 tomcat 启动的入口在哪。需要在启动类添加如下代码:
@SpringBootApplicationpublic class ApiApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(ApiApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(ApiApplication.class, args);
}}
比如我在项目中使用了 swagger,那我就需要排除 swagger 的静态文件,代码如下:
@Configurationpublic class WebMvcConfig extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
// 排除静态文件
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
// do something}
如果发布的模块引用了本项目的其他公共模块,需要先把本项目的公共模块装载到本地仓库。
操作方式,双击父模块的
install 即可,
install 成功之后,点击发布模块的
package 生成 war 包,就完成了项目的打包,如下图所示:
有了 war 包之后,只需要把单个 war 包,放入 tomcat 的 webapps 目录,重新启动 tomcat 即可,如下图所示:
项目正常运行会在 webapps 目录下生成同名的文件夹,如下图所示:
完成以上配置,就可以 happy 的访问自己发布的项目了。
答:不影响,配置的
server.port 会被覆盖,以 tomcat 本身的端口号为准,tomcat 端口号在
tomcat/config/server.xml 文件中配置。
答:因为没有执行父节点 maven 的 install 操作,install 就是把公共模块放入本地仓库,提供给其它项目使用。
答:因为没有设置启动类导致的,设置方式:
configuration><mainClass>com.bi.api.ApiApplication</mainClass></configuration> 。SpringBootServletInitializer 实现
SpringApplicationBuilder 方法,具体代码参考文中第五部分。答:这是因为 SpringBoot 版本太高,tomcat 版本太低的原因。如果你使用的是最新版的 SpringBoot,可以考虑把 tomcat 也升级为 tomcat 8.x+ 最新的版本,就可以解决这个问题。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/31557450/viewspace-2656587/ ,如需转载,请注明出处,否则将追究法律责任。