Joh*_*hnP 4 spring spring-boot
我必须在 Spring Boot 中使用公司定制的库,并想知道我是否能够在运行时创建这样的 bean 并将其添加到 Spring 应用程序上下文中。
@Bean(name = {"customConnectionFactory"})
public ConnFactory connector() {
return new SimpleConnFactory(configuration(), "prefix");
}
Run Code Online (Sandbox Code Playgroud)
所以当我被允许在启动应用程序时正常连接 bean 时,这工作得很好。现在需求发生了变化,我应该能够在运行时动态执行此操作。我做了一些研究,似乎可以将类添加到 spring 上下文运行时,但是运行返回新对象的方法如何?
可能是这样的
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4117 次 |
| 最近记录: |