从 bean factory 访问 injectee 组件

Access the injectee component from bean factory

假设我们有一个原型范围的 bean。

public class FooConfiguration {
  @Bean
  @Scope("prototype")
  public Foo foo(@Autowired Bar bar) {
    return new Foo(bar);
  }
}

我们正在将此 bean 注入 class、TheDependent

@Component
public class TheDependent {
  @Autowired
  private Foo foo;
}

不过还有一个

@Component
public class AnotherOne {
  @Autowired
  private Foo foo;
}

在每个 @Autowired 中,都会创建一个 Foo 的新实例,因为它带有 @Scope("prototype") 注释。

我想从工厂方法 FooConfiguration#foo(Bar) 访问 'dependent' class。可能吗? Spring 可以向工厂方法的参数中注入某种 context 对象,提供有关注入点的信息吗?

是的。您可以将包含所有 bean 信息的 DefaultListableBeanFactory bean 容器注入到 bean 工厂方法的参数中:

  @Bean
  @Scope("prototype")
  public Foo foo(@Autowired Bar bar , DefaultListableBeanFactory beanFactory) {
         //Get all the name of the dependent bean of this bean
         for(String dependentBean : beanFactory.getDependentBeans("foo")){
              //Get the class of each dependent bean
              beanFactory.getType(dependentBean);

         }
        return new Foo(bar);
  }