从bean工厂访问injectee组件

Cha*_*ata 7 java spring dependency-injection javabeans

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

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

我们将这个bean注入一个类,TheDependent.

@Component
public class TheDependent {
  @Autowired
  private Foo foo;
}
Run Code Online (Sandbox Code Playgroud)

但还有另外一个.

@Component
public class AnotherOne {
  @Autowired
  private Foo foo;
}
Run Code Online (Sandbox Code Playgroud)

在每个中@Autowired,Foo都创建了一个新的gets 实例,因为它是用它注释的@Scope("prototype").

我想从工厂方法访问'dependent'类FooConfiguration#foo(Bar).可能吗?Spring可以为工厂方法的参数注入某种上下文对象,提供有关注入点的信息吗?

Ken*_*han 2

是的。您可以将DefaultListableBeanFactory包含所有bean信息的spring 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);
  }
Run Code Online (Sandbox Code Playgroud)