[英]Get a bean (programmatically registered) from Spring context?
我以编程方式注册了一个 bean:
@Autowired
private GenericApplicationContext applicationContext;
[...]
applicationContext.registerBean("a0", A.class, () -> new A(0));
// make sure to set up the bean
applicationContext.getBean("a0");
当我想按名称获取此 bean 时,它可以工作并始终返回相同的实例:
applicationContext.getBean("a0");
但是当我想获取 A.class 类型的所有 bean 时,它返回一个空的 Map:
Map<String, A> as = applicationContext.getBeansOfType(A.class);
作为 = [] !!!
我正在使用 Spring 5.0,为什么 Spring 认为我的上下文中没有 A 类型的 bean 而我可以按名称检索它们?
改用BeanFactoryUtils.beansOfTypeInducingAncestors :
BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, A.class)
请参阅Spring 论坛答案:
不考虑该工厂可能参与的任何层次结构。使用 BeanFactoryUtils 的 beansOfTypeInducingAncestors 也将 bean 包含在祖先工厂中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.