Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a bean (programmatically registered) from Spring context?

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 ?

like image 837
Jonathan Avatar asked Apr 15 '26 10:04

Jonathan


1 Answers

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.

like image 188
user7294900 Avatar answered Apr 16 '26 23:04

user7294900



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!