java - Spring Boot 尝试解析不在我的 xml 中的 bean

标签 java spring spring-boot

我想测试一个简单关闭应用程序的类:

@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的工作原理。

@SpringBootApplication :

This is a convenience annotation that is equivalent to declaring @Configuration, @EnableAutoConfiguration and @ComponentScan.

@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/

相关文章:

java - 我可以在 IntelliJ 中跨过 while 循环吗?

spring - @Scheduled 线程是否终止?

spring - 从Spring依赖管理插件中提取依赖版本

java - application.yaml 文件设置字段带有 OR 条件(提供默认值)

java - 将 hibernate 查询结果转换为类类型的对象而不是列表数组

java - 按钮 b2 =stop 未监听

java - 保护有状态的 Web 服务

Spring Security : How do I reset SPRING_SECURITY_LAST_EXCEPTION. 消息?

spring - @RequestBody 与 Spring 中的 HandlerMethodArgumentResolver

java - 在 Spring [Boot] 中手动解决依赖关系