80.7 使用排除创建不可执行的JAR

如果你构建的产物既有可执行的jar和非可执行的jar,那你常常需要为可执行的版本添加额外的配置文件,而这些文件在一个library jar中是不需要的。比如,application.yml配置文件可能需要从非可执行的JAR中排除。

下面是如何在Maven中实现:

  1. <build>
  2. <plugins>
  3. <plugin>
  4. <groupId>org.springframework.boot</groupId>
  5. <artifactId>spring-boot-maven-plugin</artifactId>
  6. <configuration>
  7. <classifier>exec</classifier>
  8. </configuration>
  9. </plugin>
  10. <plugin>
  11. <artifactId>maven-jar-plugin</artifactId>
  12. <executions>
  13. <execution>
  14. <id>exec</id>
  15. <phase>package</phase>
  16. <goals>
  17. <goal>jar</goal>
  18. </goals>
  19. <configuration>
  20. <classifier>exec</classifier>
  21. </configuration>
  22. </execution>
  23. <execution>
  24. <phase>package</phase>
  25. <goals>
  26. <goal>jar</goal>
  27. </goals>
  28. <configuration>
  29. <!-- Need this to ensure application.yml is excluded -->
  30. <forceCreation>true</forceCreation>
  31. <excludes>
  32. <exclude>application.yml</exclude>
  33. </excludes>
  34. </configuration>
  35. </execution>
  36. </executions>
  37. </plugin>
  38. </plugins>
  39. </build>

在Gradle中,你可以使用标准任务的DSL(领域特定语言)特性创建一个新的JAR存档,然后在bootRepackage任务中使用withJarTask属性添加对它的依赖:

  1. jar {
  2. baseName = 'spring-boot-sample-profile'
  3. version = '0.0.0'
  4. excludes = ['**/application.yml']
  5. }
  6. task('execJar', type:Jar, dependsOn: 'jar') {
  7. baseName = 'spring-boot-sample-profile'
  8. version = '0.0.0'
  9. classifier = 'exec'
  10. from sourceSets.main.output
  11. }
  12. bootRepackage {
  13. withJarTask = tasks['execJar']
  14. }