【问题标题】:Why getting NoSuchBeanDefinitionException while unit testing the controller为什么在单元测试控制器时得到 NoSuchBeanDefinitionException
【发布时间】:2011-11-19 04:12:33
【问题描述】:

为什么会出现这个异常:

org.springframework.beans.factory.NoSuchBeanDefinitionException: 否 [org.springframework.web.servlet.HandlerAdapter] 类型的唯一 bean 已定义:预期为单个 bean,但发现为 0:

   public class MyControllerIntegrationTest {
Logger logger = Logger.getLogger(MyControllerIntegrationTest.class);
@Autowired
private ApplicationContext applicationContext;

private MockHttpServletRequest request;
private MockHttpServletResponse response;
private HandlerAdapter handlerAdapter;
private TestExceptionController controller;

@Before
public void setUp() {
    request = new MockHttpServletRequest();
    response = new MockHttpServletResponse();
    handlerAdapter = applicationContext.getBean(HandlerAdapter.class);

    controller = new TestExceptionController();
}

我正在尝试运行上面的代码。我的应用程序上下文已加载并收到上述异常消息。请指导,我应该在bean定义文件中添加一些bean定义吗?

【问题讨论】:

  • 错误不是不言自明吗?您的测试上下文中没有 HandlerAdapter 类型的 bean。您应该向我们展示整个测试,包括类注释以及测试上下文文件。

标签: java spring


【解决方案1】:

您可能应该使用the ApplicationContextAware interface,或者更改您的代码以直接注入 HandlerAdapter(通过将@Autowired 注释移动到该字段)而不是从应用程序上下文中获取它。 (除非它是一个原型,而不是一个单例,而且你真的需要在每个单元测试中都有一个新实例。)

【讨论】:

    【解决方案2】:

    从 Spring 3.0.7 升级到 Spring 3.1 时,我遇到了同样的问题。

    我用这个答案解决了这个问题:How to unit test a Spring MVC annotated controller?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多