2017-06-16 72 views
0

我必须在Spring Boot中使用公司定制的库,并且想知道我是否能够在运行时像这样创建bean并将其添加到Spring应用程序上下文中。使用方法动态创建Spring bean使用方法

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

所以这个工作正常,当我被允许通常在启动应用程序时连线bean。现在需求已经改变,我应该能够做到这一点动态运行时。我已经做了一些研究,似乎可以向Spring上下文运行时添加类,但运行返回新对象的方法怎么样?

回答

1

可能是这样的

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); 
+0

谢谢,我不知道我可以创建一个对象,并线,为应用程序上下文。 – JohnP