簡體   English   中英

Spring Boot試圖解決不在我的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工作的。

@SpringBootApplication

這是一個方便注釋,等效於聲明@Configuration, @ EnableAutoConfiguration和@ComponentScan

@ComponentScan

如果未定義特定的程序包, 則將從聲明此批注的類的程序包中進行掃描

因此,將拾取ShutdownManagerTest的相同或子程序包中的所有內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM