![](/img/trans.png)
[英]How to inject Spring boot Environment bean to Custom Spring xml bean?
[英]Spring Boot trying to resolve bean not in my xml
我想测试一个简单地关闭应用程序的类:
@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。 但这在我的仅包含一个bean的测试xml中未定义。
有人可以帮我理解为什么它试图解析不在上下文中的bean吗?
这样做是因为@SpringBootApplication
就是@SpringBootApplication
工作的。
这是一个方便注释,等效于声明@Configuration, @ EnableAutoConfiguration和@ComponentScan 。
如果未定义特定的程序包, 则将从声明此批注的类的程序包中进行扫描 。
因此,将拾取ShutdownManagerTest的相同或子程序包中的所有内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.