【已解决】使用JWT令牌时:Exception in thread “main“ java.lang.NoSuchMethodError: ‘java.lang.String org.junit.pl
·
// 生成jwt令牌
@Test
public void testGenJwt() {
Map<String, Object> claims = new HashMap<>();
claims.put("id", 1);
claims.put("username", "admin");
String jwt = Jwts.builder()
.signWith(SignatureAlgorithm.HS256, "admit") //签名算法
.setClaims(claims) ///自定义内容
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60)) //设置过期时间为1h
.compact();
System.out.println(jwt);
}
(来自黑马程序员javaweb,Day12-07,令牌生成和校验)
生成令牌时出现错误

首先我们需要检查一下生成jwt令牌的依赖有没有引入,在pom.xml文件查看,是否引入依赖
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
出现这个错误,是因为主包用的idea是2022的,JUnit 5 最高只支持到 5.8.x 版本,不支持 6.0.3,( IDE 和依赖版本兼容性问题)所以我们只需要降低JUnit的版本就可以了
在pom.xml中,可以看到主包的父工程文件版本是4.0.3
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.0.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
测试类的依赖spring-boot-starter-test 没有显式指定版本,由 Spring Boot 父 POM 管理,但是Spring Boot 4.0.3 默认包含 JUnit 6.0.3,这和我的IDEA 2022 不兼容
那我们降低版本到5.9x或者5.8x
在 pom.xml 中添加 JUnit 版本覆盖配置:
在<properties>加入下面两行代码:
<junit-jupiter.version>5.9.3</junit-jupiter.version> <junit-platform.version>1.9.3</junit-platform.version>

然后再在测试类依赖下面加入:
<exclusions>
<exclusion>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
</exclusion>
<exclusion>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
</exclusion>
</exclusions>

再加上这两个依赖:
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.9.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<version>1.9.3</version>
<scope>test</scope>
</dependency>

添加完之后别忘记刷新依赖

重新运行测试类

个人开发中遇到的一些问题,如果问豆姐解决不了,可以参考一下主包的方法
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐



所有评论(0)