使用方法在运行时动态创建 Spring bean

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 上下文运行时,但是运行返回新对象的方法如何?

Sta*_*avL 6

可能是这样的

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)

  • 这三个步骤有详细的说明吗?每个的意义是什么?如果我们制作多个相同类型的豆子,有什么特殊处理吗? (2认同)