[英]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.