In Spring Boot 2.6, circular references are now prohibited by default. However, the effects of this change are not obvious. In the following example, Bar
is no longer found. In 2.5 they were found.
Code like this caused an issue in production that was not immediately detected because there were no errors either during startup or runtime.
It would be very helpful if Spring could provide any kind of feedback or warning when it has decided not to find beans due to this setting. Similar to how Spring refuses to start if you have a circular dependency.
@Service
@RequiredArgsConstructor
public class Foo {
private final ApplicationContext applicationContext;
@PostConstruct
public void init() {
var bars = applicationContext.getBeansOfType(Bar.class);
// .stream() bars and do stuff with them.
}
}
@Service
@RequiredArgsConstructor
public class Bar {
private final Foo foo;
}
Comment From: snicoll
Thanks for the report. I am assuming that the trip down example is not providing the full picture of why you're doing this but Bar
injecting Foo
in its constructor is really problematic. It also looks like that doing the getBeansByType
business in @PostConstruct
could be a way to avoid the cycle. It actually isn't. A bean is considered to be fully initialized once properties are set and initialization callbacks have been invoked.
Finally, you should not inject the ApplicationContext
for this, but the BeanFactory
. Doing so will provide a more narrowed and "guided" view of the API you're supposed to use. In particular getBeansOfType
won't be available. I've done some trials with your sample and they all fail with an unresolved circular reference. The reason why getBeansOfType doesn't is because it accepts to ignore a bean that couldn't be initialized at the point where the method is invoked. If you call getBeanProvider
and you try to consume the stream you'll get the error I've mentioned above.
All in all, the example above doesn't represent a valid scenario, even with circular references allowed so I am going to close this now. Please review the advices above and update your configuration.