如何通过Spring Boot Maven Plugin排除依赖及其传递依赖?
问题描述
我有一个可在Azure或GCP环境运行的Spring Boot应用,通过Spring Profile控制特定云提供商的Bean创建,使用Maven结合Spring Boot Maven Plugin构建可执行JAR。该应用同时引入了Azure和GCP SDK,希望通过Maven Profile构建对应云提供商的专属可执行JAR。
按照Spring Boot Maven Plugin的说明,目前可以:
- 排除由
groupId和artifactId(必要时指定classifier)标识的特定构件; - 排除属于指定
groupId的所有构件。
但上述方式仅能排除匹配条件的直接构件,我还需要同时排除这些构件的传递依赖,请问如何通过Spring Boot Maven Plugin实现这一需求?
解决方案
要同时排除目标SDK的直接依赖及其所有传递依赖,可通过两种实用方式实现:
方式一:Maven Profile移除依赖+打包排除配合
- 定义Maven Profile,针对不同云环境移除对方SDK的依赖:
<profiles> <!-- Azure专属Profile --> <profile> <id>azure</id> <dependencies> <!-- 移除GCP SDK的BOM依赖及所有子依赖 --> <dependency> <groupId>com.google.cloud</groupId> <artifactId>spring-cloud-gcp-dependencies</artifactId> <version>4.8.1</version> <type>pom</type> <scope>import</scope> <exclusions> <exclusion> <groupId>*</groupId> <artifactId>*</artifactId> </exclusion> </exclusions> </dependency> </dependencies> </profile> <!-- GCP专属Profile --> <profile> <id>gcp</id> <dependencies> <!-- 移除Azure SDK的BOM依赖及所有子依赖 --> <dependency> <groupId>com.azure.spring</groupId> <artifactId>azure-spring-boot-bom</artifactId> <version>4.15.0</version> <type>pom</type> <scope>import</scope> <exclusions> <exclusion> <groupId>*</groupId> <artifactId>*</artifactId> </exclusion> </exclusions> </dependency> </dependencies> </profile> </profiles>
- 配置Spring Boot Maven Plugin的打包排除规则,确保无漏网依赖:
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <executions> <execution> <goals> <goal>repackage</goal> </goals> <configuration> <excludes> <exclude> <groupId>com.google.cloud</groupId> <artifactId>*</artifactId> </exclude> <exclude> <groupId>com.azure.spring</groupId> <artifactId>*</artifactId> </exclude> </excludes> </configuration> </execution> </executions> </plugin> </plugins> </build>
方式二:Profile控制依赖引入(更高效)
从根源上避免引入不需要的依赖,仅在对应Profile中引入目标云SDK:
<dependencyManagement> <dependencies> <!-- 统一管理SDK版本,不直接引入 --> <dependency> <groupId>com.azure.spring</groupId> <artifactId>azure-spring-boot-starter</artifactId> <version>4.15.0</version> </dependency> <dependency> <groupId>com.google.cloud</groupId> <artifactId>spring-cloud-gcp-starter</artifactId> <version>4.8.1</version> </dependency> </dependencies> </dependencyManagement> <profiles> <profile> <id>azure</id> <dependencies> <!-- 仅引入Azure SDK --> <dependency> <groupId>com.azure.spring</groupId> <artifactId>azure-spring-boot-starter</artifactId> </dependency> </dependencies> </profile> <profile> <id>gcp</id> <dependencies> <!-- 仅引入GCP SDK --> <dependency> <groupId>com.google.cloud</groupId> <artifactId>spring-cloud-gcp-starter</artifactId> </dependency> </dependencies> </profile> </profiles>
这种方式无需额外配置打包排除,直接从依赖层面切断了不必要的依赖树。
内容的提问来源于stack exchange,提问作者pradhan
相关产品推荐
相关产品推荐

