問題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.Bar
ui
添加兩個額外的註解後this
@RunWith(SpringRunner.class) @SpringBootTest @ComponentScan @ImportAutoConfiguration public class FooTest
會去調用以下方法 注入fooTest.Bar
到beanDefinitionNames
中spa
org.springframework.beans.factory.support.DefaultListableBeanFactory#registerBeanDefinition
對應的調用棧信息 調試