java - 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?
解决方案
发生这种情况的原因是您的Config
注释正在查找子包以查找 bean,但它无法再找到它们。
如果您使用Config
a 注释您的静态类,@ComponentScan("package.of.your.helloController")
那么您的控制器将再次找到它。
推荐阅读
- cordova - Ionic cordova build android错误:无法确定任务':app:compileDebugJavaWithJavac'的依赖关系
- google-drive-api - 使用 Google API 列表从共享子文件夹中获取文件列表
- opencv - 操作 JavaCamera2View 为相机设备设置参数 - Android 中的 OpenCV
- azure-functions - 如何查看和检查部署到 Azure 应用服务计划的容器化“Azure 函数”
- javascript - 带有 SVG 图标的 Chrome 扩展 (chrome.browserAction.setIcon)
- javascript - 尝试遍历第一个对象并将当前项目添加到另一个对象中
- android - Android Studio / Firestore:Firestore Boolean在RecyclerView中TextView的机会颜色?
- c# - 碰撞后不能让我的游戏对象改变位置
- r - 使用 NAs R 滚动累积产品
- python - model.fit(X_train, y_train, epochs=5, validation_data=(X_test, y_test) 不工作