测试类中的静态内部类识别不到(NoSuchBeanDefinitionException)解决
文章目录
问题
测试类里面的静态内部类识别不到
@RunWith(SpringRunner.class)
@SpringBootTest
public class FooTest {
@Autowired
private Bar bar;
@Test
public void bar() {
}
@Component
public static class Bar {
}
}
当执行bar测试方法的时候 报错:
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
添加两个额外的注解后
@RunWith(SpringRunner.class)
@SpringBootTest
@ComponentScan
@ImportAutoConfiguration
public class FooTest
会去调用如下方法 注入fooTest.Bar到beanDefinitionNames中
org.springframework.beans.factory.support.DefaultListableBeanFactory#registerBeanDefinition
对应的调用栈信息
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论