springboot version:2.4.13
spring-boot-starter-test version: 2.4.13
question
when use @SpyBean, it not support circular bean
eg:
@Component
public class A {
@Autowired
private B b;
public String getName() {
return A.class.getName();
}
public int getAge() {
return 18;
}
}
@Component
public class B {
@Autowired
private A a;
public String getName() {
return B.class.getName();
}
}
@SpringBootTest
public class TestCycle {
@SpyBean
private A a;
@Test
public void test() {
Mockito.doReturn("name").when(a).getName();
Assertions.assertEquals("name", a.getName());
Assertions.assertEquals(18, a.getAge());
}
}
exception:
Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'a': Bean with name 'a' has been injected into other beans [b] in its raw version as part of a circular reference, but has eventually been wrapped. This means that said other beans do not use the final version of the bean. This is often the result of over-eager type matching - consider using 'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.
Comment From: wilkinsona
Thanks for the report but Spring Boot 2.4.x is no longer supported. We also do not recommend relying on circular dependencies between beans and support for them has been disabled by default since Spring Boot 2.6. To break a cycle between dependencies, Spring Framework has to inject a bean in its non-final form – this is what the error message is describing – and this can prevent certain features such as @SpyBean from working. Unfortunately, there's nothing we can do about this and the recommended course of action is to restructure your application to remove the cycle.