我想测试一个简单关闭应用程序的类:
@Component
public class ShutdownManager {
@Autowired
private ApplicationContext applicationcontext;
public int shutdown(int returnCode) {
return SpringApplication.exit(applicationcontext, () -> returnCode);
}
}
我创建的测试用例是这样的:
public class ShutdownManagerTest {
@Test
public void should_shutdown_gracefully() {
SpringApplication app = new SpringApplication(TestClass.class);
ConfigurableApplicationContext context = app.run();
ShutdownManager shutdownManager = (ShutdownManager)context.getBean("shutdownManager");
int result = shutdownManager.shutdown(10);
assertThat(result).isEqualTo(10);
}
@SpringBootApplication
@ImportResource("classpath:/core/shutdownmanagertest.xml")
private static class TestClass {
public TestClass() {
}
public static void main(String[] args) {
}
}
}
我的 shutdownmanagertest.xml 仅包含一个 bean:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="shutdownManager" class="com.mycodebase.ShutdownManager" />
</beans>
但是,当我运行它时,它提示:
Field myOtherService in com.mycodebase.MyTask required a bean of type 'com.mycodebase.MyOtherService ' that could not be found.
类 MyTask 与 ShutdownManager 位于同一包中,其中包含一个带有 @Autowire 注释的字段 myOtherService。但它没有在我的测试 xml 中定义,它只包含一个 bean。
有人可以帮助我理解为什么它试图解析不在上下文中的 bean 吗?
最佳答案
它这样做是因为这就是@SpringBootApplication
的工作原理。
This is a convenience annotation that is equivalent to declaring @Configuration, @EnableAutoConfiguration and @ComponentScan.
If specific packages are not defined, scanning will occur from the package of the class that declares this annotation.
因此,ShutdownManagerTest 的同一包或子包中的所有内容都将被拾取。
关于java - Spring Boot 尝试解析不在我的 xml 中的 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56738442/