springboot单元测试报错,Error creating bean with name 'requestMappingHandlerAdapter'

本文介绍了在SpringBoot单元测试时遇到的'Error creating bean with name 'requestMappingHandlerAdapter''错误,分析了可能是由于包冲突或缺失导致。通过运行maven dependency:tree命令定位问题,发现在nimbus-jose-jwt库中存在json-smart版本冲突。解决方法是在pom.xml中排除json-smart的冲突依赖。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当使用springboot 进行单元测试的时候,发生了错误。


@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@WebAppConfiguration
public class ServiceTest{

    @Test
    public void testApp(){
      
    }
}

报错如下:

java.lang.IllegalStateException: Failed to load ApplicationContext
    ...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerAdapter' defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter]: Factory method 'requestMappingHandlerAdapter' threw exception; nested exception is java.lang.NoClassDefFoundError: net/minidev/json/writer/JsonReaderI
    ...
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter]: Factory method 'requestMappingHandlerAdapter' threw exception; nested exception is java.lang.NoClassDefFoundError: net/minidev/json/writer/JsonReaderI
    ...
Caused by: java.lang.NoClassDefFoundError: net/minidev/json/writer/JsonReaderI
    ...
Caused by: java.lang.ClassNotFoundException: net.minidev.json.writer.JsonReaderI
    ...

从classnotfoundException可以猜到有可能是包冲突或者少包了。

所以使用maven查看maven tree。

在idea中可以直接使用terminal命令行输入以下命令

mvn dependency:tree -dverbose>temp/tree.txt

该命令是打印详细的maven tree 并放入当前目录下的temp目录下的tree.txt (需要自己新建temp目录)

打印到txt中更加方便排查。

  • 最后写着compile的就是编译成功的
  • 最后写着omitted for duplicate的就是有JAR包被重复依赖了,但是JAR包的版本是一样的
  • 最后写着omitted for conflict with xx的,说明和别的JAR包版本冲突了,该行的JAR包不会被引入

 因此我们查找 conflict关键字可以发现:

json-smart 在这里冲突了,不会被引入。

而json-smart中在nimbus-jose-jwt中也被引入了,版本是1.3.1。

因此spring-boot-start-test中的json-smart不会被引入,从而导致了异常。

 

解决方法:

在pom.xml中找到nimbus-jose-jwt的依赖,加上:

<exclusions>
     <exclusion>
          <groupId>net.minidev</groupId>
          <artifactId>json-smart</artifactId>
      </exclusion>
</exclusions>

去除掉这个依赖就ok啦。

### Spring Boot WebSocket Bean Creation Error When encountering an error while creating a bean named `webSocketHandlerMapping` in a Spring Boot application using WebSocket, several factors could contribute to this issue. The configuration settings provided offer insights into resource handling but do not directly address WebSocket configurations[^1]. However, understanding how beans are configured and managed within the context of WebSockets is crucial. In Spring Boot applications utilizing WebSocket, ensuring proper registration of handlers and mappings plays a vital role. If there's an error during the creation of the `webSocketHandlerMapping` bean, it often indicates misconfiguration or missing dependencies related specifically to WebSocket support rather than general resource management settings mentioned earlier. To resolve issues surrounding the creation of the `webSocketHandlerMapping` bean: - Verify that all necessary WebSocket-related dependencies have been included in the project’s build file (e.g., Maven POM or Gradle). - Ensure correct annotations such as `@EnableWebSocket`, along with appropriate handler classes implementing interfaces like `WebSocketHandler`. - Check for any conflicting configurations between standard MVC components and those specific to WebSocket functionality. Additionally, when configuring controllers interacting over WebSocket connections, consider patterns similar to RESTful service implementations where methods respond appropriately based on incoming requests[^2]: ```java @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(myWebSocketHandler(), "/ws").setAllowedOrigins("*"); } @Bean public MyWebSocketHandler myWebSocketHandler() { return new MyWebSocketHandler(); } } ``` For comprehensive testing purposes concerning asynchronous behaviors associated with WebSocket communications, tools listed provide valuable assistance through simplifying test scenarios involving concurrency and network interactions without relying solely upon actual external services[^3]: ```java // Example Test Using Awaitility for Asynchronous Operations Verification @Test public void shouldReceiveMessageViaWebSocket() throws Exception { given(). contentType(JSON). body(new Message("test"). expect(). statusCode(200); await().atMost(5, TimeUnit.SECONDS).until(() -> !receivedMessages.isEmpty()); } ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值