首页 > 解决方案 > Spring 无法使用内部类解决依赖关系

问题描述

今天我在网上遇到了另一个可怜的灵魂学习春天。我决定我会帮助他们。与 Spring 一样古老的故事,单元测​​试中缺少的 bean。我做了一个快速修复,我用丢失的 bean 进行了配置,它工作了,看起来一切都很好。

@Configuration
class Config {
    @Bean
    HelloService getHelloService() {
        return new HelloService();
    }
}

@ExtendWith(SpringExtension.class)
@WebMvcTest(HelloController.class)
@Import({Config.class})
class HelloControllerIntTest {

    @Autowired
    private MockMvc mvc;


    @Test
    void hello() throws Exception {
        RequestBuilder request = get("/hello");
        MvcResult result = mvc.perform(request).andReturn();
        assertEquals("Hello, World", result.getResponse().getContentAsString());
    }

    @Test
    public void testHelloWithName() throws Exception {
        mvc.perform(get("/hello?name=Dan"))
                .andExpect(content().string("Hello, Dan"));
    }
}

再想一想,用额外的、非常通用的类来污染公共空间并不是一个好主意,所以我决定把它放在类里面。

@ExtendWith(SpringExtension.class)
@WebMvcTest(HelloController.class)
@Import({HelloControllerIntTest.Config.class})
class HelloControllerIntTest {

   @Configuration
   static class Config {
    @Bean
    HelloService getHelloService() {
        return new HelloService();
    }
   }

    @Autowired
    private MockMvc mvc;


    @Test
    void hello() throws Exception {
        RequestBuilder request = get("/hello");
        MvcResult result = mvc.perform(request).andReturn();
        assertEquals("Hello, World", result.getResponse().getContentAsString());
    }

    @Test
    public void testHelloWithName() throws Exception {
        mvc.perform(get("/hello?name=Dan"))
                .andExpect(content().string("Hello, Dan"));
    }
}

令我惊讶的是,它不起作用,404错误。我在 中放了一个断点,HelloController似乎根本没有构建 bean。我还查看了 bean 的定义,似乎第一个版本有 91 个 bean,第二个版本有 88 个,所以我们那里缺少 bean。

任何想法这里发生了什么?为什么在第二个版本中 Spring 忽略了 HelloController?

标签: javaspringspring-boot

解决方案


发生这种情况的原因是您的Config注释正在查找子包以查找 bean,但它无法再找到它们。

如果您使用Configa 注释您的静态类,@ComponentScan("package.of.your.helloController")那么您的控制器将再次找到它。


推荐阅读