I would like to create custom child context from some configuration and additionally add some beans to it programmatically.
I read answer https://stackoverflow.com/a/4540762/258483 about BeanDefinitionRegistryPostProcessor
but don't understand how to use it. If I write implementation of BeanDefinitionRegistryPostProcessor
then what to do with it next? Add to context? But this is the question: how to add bean to context! If I would be able to add BeanDefinitionRegistryPostProcessor
to context, then why I would ask how to add beans?
The problem is that I have context and want to add bean to it.
I know I can instantiate beans and autowire them with
Context#getAutowireCapableBeanFactory().createBean(klass);
but this apparently just wires class, but not adds it to context?
From Spring 5.0
onwards, you can register your beans dynamically directly using the ApplicationContext
.
GenericApplicationContext ac = ....;
// example
ac.registerBean("myspecialBean", Integer.class, () -> new Integer(100));
// using BeanDefinitionCustomizer
ac.registerBean("myLazySpecialBean", Integer.class, () -> new Integer(100), (bd) -> bd.setLazyInit(true));
See the javadoc here for different APIs for registerBean
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With