SpringBoot项目打包成war,并且Tomcat可以读取外置的文件
Springboot项目内置Tomcat一般情况下不需要在进行tomcat的配置,在一些特殊的场景下,需要用到tomcat进行部署的时候,就需要我们进行一些配置了,让项目可以在tomcat上面运行,并且可以将yml文件放在外面,提供给我们进行动态修改
部署tomcat

可能出现中文乱码的可能记得修改这些地方

在idea64.exe.vmoptions里面添加
-Dfile.encoding=UTF-8
注:不要修改错了,修改错了可能导致idea启动不起来
修改SpringBoot项目
首先需要在pom文件中进行修改,在build中添加finalName可以将war包进行打包的时候以其命名,中则是将yml文件从项目中排除
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- 移除嵌入式tomcat插件 -->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-servlet-api</artifactId>
<version>8.5.83</version>
<scope>provided</scope>
</dependency>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>*.properties</exclude>
<exclude>*.yml</exclude>
<exclude>*.xml</exclude>
</excludes>
</resource>
</resources>
<finalName>HKEstuaryCenter</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
在项目里面自定义一个EnvironmentPostProcessor用来读取外部的yml文件,将其放在了tomcat文件夹下面conf中
public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor {
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
//tomcat路径
String property = System.getProperty("catalina.home");
String path = property + File.separator + "conf" + File.separator + "外部配置.yml";
//Springboot读取yml配置
YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
yaml.setResources(new FileSystemResource(path));
MutablePropertySources propertySources = environment.getPropertySources();
propertySources.addFirst(new PropertiesPropertySource("Config", yaml.getObject()));
}
}
在resources下面添加一个META-INF文件夹里面放置一个spring.factories文件,让其调用自定义的EnvironmentPostProcessor
org.springframework.boot.env.EnvironmentPostProcessor=com.dahua.config.MyEnvironmentPostProcessor
最后war包可以直接放在webapps下面,之后就去启动项目吧!
本文介绍如何将SpringBoot项目打包成WAR文件,并在Tomcat上部署,同时实现外部YML配置文件的动态加载。
9553

被折叠的 条评论
为什么被折叠?



