如何从spring boot jar中排除资源文件?

时间:2015-09-29 09:43:16

标签: java maven spring-boot

我正在使用maven-spring-boot插件来生成jar。我有多个配置资源文件(application-production.yml, application-test.yml, application-development.yml)。

事情是,当我为客户生成版本时,我想排除开发和测试文件。是否可以在maven-spring-boot插件中排除资源文件?

我试过了:

        <build>
            <resources>
                <resource>
                    <directory>src/main/resources</directory>
                    <excludes>
                        <exclude>application-dev*</exclude>
                        <exclude>application-test*</exclude>
                    </excludes>
                </resource>
            </resources>
        </build>

但maven插件使用自己的脚本进行资源管理(例如@ val @ replacement等),如果将它添加到pom中,它会在打包时失败:

Caused by: org.yaml.snakeyaml.scanner.ScannerException: while scanning for the next token
found character @ '@' that cannot start any token. (Do not use @ for indentation)
 in 'reader', line 4, column 18:
    project.version: @project.version@
没有它,它可以正常工作。

3 个答案:

答案 0 :(得分:6)

使用maven-resource插件和maven配置文件,而不是使用maven-spring-boot插件:

<profiles>
  <profile>
    <id>prod</id>
    <build>
      <resources>
        <resource>
          <filtering>true</filtering>
          <directory>[your directory]</directory>
          <excludes>
            <exclude>[non-resource file #1]</exclude>
            <exclude>[non-resource file #2]</exclude>
            <exclude>[non-resource file #3]</exclude>
            ...
            <exclude>[non-resource file #n]</exclude>
          </excludes>
        </resource>
      </resources>
    </build>
  </profile>
</profiles>

确保在资源元素中指定<filtering>true</filtering>选项。

为每个环境创建一个配置文件并过滤这些文件。

确保使用正确的配置文件执行maven:

mvn clean install -P prod

要查看maven-resource插件的更多示例,请查看maven-resource

如果您想了解有关个人资料的更多信息,请查看profiles

答案 1 :(得分:5)

Spring Boot Maven插件将Maven JAR插件创建的JAR文件重新打包。因此,您还可以选择在首次构建JAR时简单地排除文件,从而避免Spring Boot Maven插件首先找到它们:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>3.1.0</version>
    <configuration>
        <excludes>
             <exclude>application-dev*</exclude>
             <exclude>application-test*</exclude>
        </excludes>
    </configuration>
</plugin>

答案 2 :(得分:0)

使用maven-resources-plugin,它支持排除标记。

顺便问一下,为什么你需要使用三个yaml文件?你可以在一个带有“---”和spring.profiles的application.yaml文件中编写这些配置,例如:

memcached.addresses: test03:11211
spring.profiles.active: dev
---
# dev
spring:
    profiles: dev
logging.access.enabled: false
---
# test
spring:
    profiles: test
logging.config: classpath:log4j.test.properties
logging.access.dir: /home/shared/log
---
# online
spring:
    profiles: online
logging.config: classpath:log4j.online.properties
logging.access.dir: /home/shared/log
相关问题