測試類中的靜態內部類識別不到(NoSuchBeanDefinitionException)解決

問題java

測試類裏面的靜態內部類識別不到spring

@RunWith(SpringRunner.class)
@SpringBootTest
public class FooTest {
    @Autowired
    private Bar bar;
    @Test
    public void bar() {
        
    }

    @Component
    public static class Bar {
    }

}

當執行bar測試方法的時候 報錯:app

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.my.app.dao.FooTest$Bar' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1654) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]

解決
通過斷點調試發現測試

org.springframework.beans.factory.support.DefaultListableBeanFactory#doGetBeanNamesForType

this.beanDefinitionNames並無fooTest.Barui

添加兩個額外的註解後this

@RunWith(SpringRunner.class)
@SpringBootTest
@ComponentScan
@ImportAutoConfiguration
public class FooTest

會去調用以下方法 注入fooTest.BarbeanDefinitionNamesspa

org.springframework.beans.factory.support.DefaultListableBeanFactory#registerBeanDefinition

對應的調用棧信息 調試

圖片描述

相關文章
相關標籤/搜索