Spring Boot 项目默认的会将所有资源文件、依赖文件、配置文件等打包成单一的 jar 文件,但是有时候我们并不想让配置文件、依赖包都跟可执行文件打包到一起。
这时候可以在 pom.xml 文件中进行配置,从而使资源文件、依赖包和可执行文件分离。
本文主要是分离配置文件,pom.xml配置如下:
<build><!-- 资源配置 --><resources><resource><filtering>true</filtering><directory>src/main/resources</directory><!--排除配置文件--><excludes><!--使用通配符,当然可以定义多个exclude标签进行排除--><exclude>**/application*.yml</exclude></excludes></resource></resources><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>${spring-boot-dependencies.version}</version><executions><execution><goals><goal>repackage</goal></goals></execution></executions></plugin><!-- 资源文件处理插件 --><plugin><artifactId>maven-resources-plugin</artifactId><executions><!-- 复制配置文件 --><execution><id>copy-resources</id><phase>package</phase><goals><goal>copy-resources</goal></goals><configuration><!-- 复制配置文件到指定目录 --><resources><resource><directory>src/main/resources</directory><includes><include>**/application*.yml</include></includes></resource></resources><outputDirectory>${project.build.directory}/config</outputDirectory></configuration></execution></executions></plugin></plugins>
</build>
打包时使用 resources 的 exclude 排除指定的资源文件,使用 maven-resources-plugin 将配置文件输出到外部目录。
启动 jar 时使用以下命令即可启动:
java -Dloader.path=config/ -jar xxxx.jar
如果是有依赖文件可以逗号分隔:
java -Dloader.path=lib/,config/ -jar xxxx.jar