Hi,
DefaultListableBeanFactory#getBeansOfType
catches and swallows BeanCreationException
. The method documentation and name creates the assumption, that getBeansOfType has the same behiour like
for (String beanName : listableBeanFactory.getBeanNamesForType(type)) {
Object bean = listableBeanFactory.getBean(beanName);
}
But the result is totally differnt. This behaviour is not well documented and unexpected to the client.
Best greetings, Ben
Comment From: jhoeller
getBeansOfType
suppresses exceptions for circular reference scenarios where the root cause is a BeanCurrentlyInCreationException
, is this what you mean? That should not be common at all but obviously you might run into it. In any case, we can't change that behavior due to backwards compatibility concerns, so we can only really document it.
Note that we generally recommend getBeanNamesForType
with explicit bean instance retrieval, also for potentially lazy bean creation purposes. I suppose we should document that recommendation as well.
Comment From: bekoenig
Hello @jhoeller,
getBeansOfType
also suppresses UnsatisfiedDependencyException
. In my scenario, this bean depends on a bean provided by a later processed starter. To indicate an implementation error, an exception should be thrown. However, currently, this bean seems to be incorrectly configured or not found by my starter.
I will change my implementation to getBeanNamesForType
and getBean
for fail-fast.
Thank you!
Comment From: jhoeller
It only suppresses UnsatisfiedDependencyException
if the root cause is a BeanCurrentlyInCreationException
, and even then only if the affected target bean is still in creation at the point of evaluating the exception (check the implementation of DefaultListableBeanFactory.getBeansOfType
). Otherwise, it rethrows the exception. I can see that this might be unexpected in some scenarios but I'm afraid it's already tightened to only do what's absolutely necessary for handling circular reference scenarios.
I'll reopen this issue for adding some javadoc notes to getBeansOfType
, including a recommendation to consider getBeanNamesForType
as an alternative.
Comment From: bekoenig
Your improvement on javadoc is good and clear enough. I think this note would have prevented my bug.