Spring Boot连接Azure Service Bus Queue时出现NoSuchMethodError错误
我正在开发一个从Azure Service Bus队列消费消息的Spring Boot应用,已按照官方文档配置了application.properties中的以下属性:
spring.cloud.azure.servicebus.namespace spring.cloud.azure.servicebus.entity-name spring.cloud.azure.servicebus.entity-type
使用环境:Java 17、最新版本的Spring Boot和Azure依赖,本地已成功执行az login命令。
但启动应用时出现如下错误日志:
2024-04-01T12:34:38.528-04:00 INFO 34956 --- [ctor-executor-1] c.a.i.ChainedTokenCredential : Azure Identity => Attempted credential EnvironmentCredential is unavailable. 2024-04-01T12:34:38.529-04:00 INFO 34956 --- [ctor-executor-1] c.a.i.ChainedTokenCredential : Azure Identity => Attempted credential WorkloadIdentityCredential is unavailable. 2024-04-01T12:34:38.543-04:00 WARN 34956 --- [ctor-executor-1] r.c.Exceptions : throwIfFatal detected a jvm fatal exception, which is thrown and logged below: java.lang.NoSuchMethodError: 'com.microsoft.aad.msal4j.AbstractClientApplicationBase$Builder com.microsoft.aad.msal4j.ConfidentialClientApplication$Builder.logPii(boolean)' at com.azure.identity.implementation.IdentityClientBase.getManagedIdentityConfidentialClient(IdentityClientBase.java:393) ~[azure-identity-1.11.2.jar:1.11.2] at com.azure.identity.implementation.IdentityClient.lambda$getManagedIdentityConfidentialClientApplication$5(IdentityClient.java:141) ~[azure-identity-1.11.2.jar:1.11.2] at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:45) ~[reactor-core-3.6.3.jar:3.6.3] ...
尝试通过环境变量配置凭据后,仍抛出相同异常,希望解决连接ASB队列并消费消息的问题。
这个错误是依赖版本冲突导致的,具体是msal4j库版本不兼容azure-identity的依赖需求,以下是具体解决步骤:
统一Spring Cloud Azure依赖版本
用Spring Cloud Azure的BOM管理所有Azure相关依赖版本,避免版本不一致。在pom.xml中添加:<dependencyManagement> <dependencies> <dependency> <groupId>com.azure.spring</groupId> <artifactId>spring-cloud-azure-dependencies</artifactId> <version>4.15.0</version> <!-- 版本需匹配你的Spring Boot版本,比如Spring Boot 3.2.x对应此版本 --> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>排查并排除冲突的msal4j依赖
执行mvn dependency:tree查看依赖树,找到所有com.microsoft.azure:msal4j的引用,排除版本较低或不兼容的实例。例如:<dependency> <groupId>xxx</groupId> <artifactId>xxx</artifactId> <exclusions> <exclusion> <groupId>com.microsoft.azure</groupId> <artifactId>msal4j</artifactId> </exclusion> </exclusions> </dependency>验证本地登录账号权限
确认az login的账号拥有Azure Service Bus队列的读取权限(如Azure Service Bus Data Receiver角色),可通过az role assignment list --assignee <你的账号> --resource-group <资源组名>验证权限是否存在。显式指定兼容的azure-identity版本
若仍有冲突,可在pom.xml中显式声明与Spring Cloud Azure BOM匹配的azure-identity版本:<dependency> <groupId>com.azure</groupId> <artifactId>azure-identity</artifactId> <version>1.12.0</version> <!-- 版本需与Spring Cloud Azure BOM保持一致 --> </dependency>
内容的提问来源于stack exchange,提问作者Earnie Dyke

