【问题标题】:Creating Spring beans dynamically runtime using method使用方法动态创建 Spring bean
【发布时间】:2017-11-19 07:56:52
【问题描述】:

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

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

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

【问题讨论】:

    标签: spring spring-boot


    【解决方案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);
    

    【讨论】:

    • 谢谢,我不知道我可以创建一个对象并将其连接到应用程序上下文。
    • 三个步骤的详细信息?每个的意义是什么?如果我们要制作多个相同类型的豆子,有什么特殊处理吗?
    • 谢谢!它有效并节省了很多时间。
    猜你喜欢
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-22
    • 1970-01-01
    • 1970-01-01
    • 2016-02-20
    • 1970-01-01
    相关资源
    最近更新 更多