如何以编程方式将bean添加到Spring上下文中? [英] How to add bean programmatically to Spring context?

查看:131
本文介绍了如何以编程方式将bean添加到Spring上下文中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过某些配置创建自定义子上下文,并以编程方式向其中添加一些bean.

I would like to create custom child context from some configuration and additionally add some beans to it programmatically.

我阅读了关于BeanDefinitionRegistryPostProcessor的答案 https://stackoverflow.com/a/4540762/258483 ,但没有不了解如何使用它.如果我编写BeanDefinitionRegistryPostProcessor的实现,那么下一步该怎么做?添加到上下文?但这是一个问题:如何将bean添加到上下文中!如果我能够在上下文中添加BeanDefinitionRegistryPostProcessor,那么为什么我会问如何添加bean?

I read answer https://stackoverflow.com/a/4540762/258483 about BeanDefinitionRegistryPostProcessor but don't understand how to use it. If I write implementation of BeanDefinitionRegistryPostProcessor then what to do with it next? Add to context? But this is the question: how to add bean to context! If I would be able to add BeanDefinitionRegistryPostProcessor to context, then why I would ask how to add beans?

问题是我有上下文,想在其中添加bean.

The problem is that I have context and want to add bean to it.

我知道我可以实例化bean并使用它们自动接线

I know I can instantiate beans and autowire them with

Context#getAutowireCapableBeanFactory().createBean(klass);

但是这显然只是wires类,而不是将其添加到上下文中吗?

but this apparently just wires class, but not adds it to context?

推荐答案

Spring 5.0开始,您可以直接使用ApplicationContext动态注册bean.

From Spring 5.0 onwards, you can register your beans dynamically directly using the ApplicationContext.

GenericApplicationContext ac = ....;
// example
ac.registerBean("myspecialBean", Integer.class, () -> new Integer(100));
// using BeanDefinitionCustomizer
ac.registerBean("myLazySpecialBean", Integer.class, () -> new Integer(100), (bd) -> bd.setLazyInit(true));

请参见 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆