Spring boot @SpyBean 尝试实例化一个新的 bean,而不是在上下文中监视它

Posted

技术标签:

【中文标题】Spring boot @SpyBean 尝试实例化一个新的 bean,而不是在上下文中监视它【英文标题】:Spring boot @SpyBean tries to instantiate a new bean instead of spying the one in context 【发布时间】:2017-04-27 11:52:21 【问题描述】:

我正在尝试使用 JUnit 在 Spring Boot 中对 Spring 批处理作业进行单元测试。 我写了这个测试类,我想在其中监视 bean ItemReader:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.NONE)
@ActiveProfiles("dev", "batch", "test-jobs")
public class BatchJobTest 

    @Autowired
    private JobLauncherTestUtils jobLauncherTestUtils;

    private @Autowired @Qualifier("contactDownloadAckJob") Job contactDownloadAckTaskJob;

    @SpyBean
    private ItemReader<CrsOscContact> reader;

    @Test
    public void testJob() throws Exception 
        given(this.reader.read()).willReturn(new CrsOscContact());
        //... blah blah blah
       


当我运行这个测试时,@SpyBean 注释似乎没有完成它的工作,它应该代理已经存在于上下文中的 ItemReader bean,所以我获得了(正确的)异常,因为根据定义,如果找不到 bean,它会尝试实例化该类型的新 bean(并且我已经指定了一个接口):

org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.batch.item.ItemReader]: Specified class is an interface

我很确定 bean(ItemReader 类型)已经在上下文中,因为:

调试中,看到目标bean实例化处理正确 如果我将@SpyBean 注释更改为@Autowired 注释,则上一点的实例被正确注入

有什么提示吗?谢谢

【问题讨论】:

同时我打开了一个 Github issue,因为监视其他 bean 就像一个魅力:github.com/spring-projects/spring-boot/issues/7625 你试过这个解决方案了吗? ***.com/questions/62698827/… 【参考方案1】:

这是一个 Spring Core 问题,现已修复。

https://github.com/spring-projects/spring-boot/issues/7625

https://jira.spring.io/browse/SPR-15011

【讨论】:

以上是关于Spring boot @SpyBean 尝试实例化一个新的 bean,而不是在上下文中监视它的主要内容,如果未能解决你的问题,请参考以下文章