Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add bean programmatically to Spring context?

Tags:

java

spring

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?

like image 911
Dims Avatar asked Mar 25 '17 20:03

Dims


Video Answer


1 Answers

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

like image 72
Neo Avatar answered Oct 12 '22 23:10

Neo