Issue
I registered a bean programmatically:
@Autowired
private GenericApplicationContext applicationContext;
[...]
applicationContext.registerBean("a0", A.class, () -> new A(0));
// make sure to set up the bean
applicationContext.getBean("a0");
When I want to get this bean by name, it works and always returns the same instance:
applicationContext.getBean("a0");
But when I want to get all beans of type A.class, it returns en empty Map:
Map<String, A> as = applicationContext.getBeansOfType(A.class);
as = [] !!!
I'm working with Spring 5.0, Why does Spring consider have no bean of type A in my context while I can retrieve them by name ?
Solution
Use instead BeanFactoryUtils.beansOfTypeIncludingAncestors:
BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, A.class)
See Spring forum answer:
Does not consider any hierarchy this factory may participate in. Use BeanFactoryUtils' beansOfTypeIncludingAncestors to include beans in ancestor factories too.
Answered By - user7294900