从 Spring 上下文获取一个 bean(以编程方式注册)?
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 时,它起作用并且总是 returns 同一个实例:
applicationContext.getBean("a0");
但是当我想获取所有 A.class 类型的 beans 时,它 returns en empty Map:
Map<String, A> as = applicationContext.getBeansOfType(A.class);
as=[]!!!
我正在使用 Spring 5.0,
为什么 Spring 认为在我的上下文中没有类型 A 的 bean,而我可以通过名称检索它们?
改用BeanFactoryUtils.beansOfTypeIncludingAncestors:
BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, A.class)
Does not consider any hierarchy this factory may participate in. Use BeanFactoryUtils' beansOfTypeIncludingAncestors to include beans in ancestor factories too.
我以编程方式注册了一个 bean:
@Autowired
private GenericApplicationContext applicationContext;
[...]
applicationContext.registerBean("a0", A.class, () -> new A(0));
// make sure to set up the bean
applicationContext.getBean("a0");
当我想通过名称获取这个 bean 时,它起作用并且总是 returns 同一个实例:
applicationContext.getBean("a0");
但是当我想获取所有 A.class 类型的 beans 时,它 returns en empty Map:
Map<String, A> as = applicationContext.getBeansOfType(A.class);
as=[]!!!
我正在使用 Spring 5.0, 为什么 Spring 认为在我的上下文中没有类型 A 的 bean,而我可以通过名称检索它们?
改用BeanFactoryUtils.beansOfTypeIncludingAncestors:
BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, A.class)
Does not consider any hierarchy this factory may participate in. Use BeanFactoryUtils' beansOfTypeIncludingAncestors to include beans in ancestor factories too.