Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Spring beans dynamically runtime using method

I have to use company's custom made libraries with Spring Boot and wondering if I'm able to create bean like this in runtime and add it to Spring application context.

@Bean(name = {"customConnectionFactory"})   
public ConnFactory connector() {
    return new SimpleConnFactory(configuration(), "prefix");
}

So this worked fine when I was allowed to wire beans normally when starting the application. Now requirements have changed and I should be able to do this dynamically runtime. I've done some research and it seems that it's possible to add class to spring context runtime, but how about running method which returns new object?

like image 587
JohnP Avatar asked Jun 16 '17 13:06

JohnP


1 Answers

Could be something like this

DefaultListableBeanFactory beanFactory = //get and store the factory somewhere

MyBean newBean = new MyBean();
beanFactory.initializeBean(newBean,"TheBeanName"); //could be class' canonical name
beanFactory.autowireBeanProperties(newBean, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
beanFactory.registerSingleton("TheBeanName", newBean);
like image 109
StanislavL Avatar answered Oct 13 '22 00:10

StanislavL