5

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?

1 Answer 1

7

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I didn't know that I can create an object and wire that to application context.
any detail on the three steps? what is the significance of each? any special treatment if we were making multiple beans of the same type?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.