Access the injectee component from bean factory

Viewed 91

Suppose we have a prototype-scoped bean.

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

We're injecting this bean to a class, TheDependent.

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

But there is also another one.

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

In each @Autowired, a new instance of Foo gets created because it's annotated with @Scope("prototype").

I would like to access the 'dependent' class from the factory method, FooConfiguration#foo(Bar). Is it possible? Can Spring inject me some sort of context object to the parameters of the factory method, providing information about the point of injection?

1 Answers

Yes. You can inject DefaultListableBeanFactory which is the spring bean container containing all the bean informations to the parameters of the bean factory method :

  @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);
  }
Related