Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access the injectee component from bean factory

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?

like image 807
Buğra Ekuklu Avatar asked Dec 27 '18 11:12

Buğra Ekuklu


People also ask

How do you get the BeanFactory reference in any class?

I can have my class implement BeanFactoryAware to get a reference to my beanfactory. Then I can do beanFactory. getBean("name"); to get access to a single bean.

How does BeanFactory work in Spring?

BeanFactory uses Beans and their dependencies metadata to create and configure them at run-time. BeanFactory loads the bean definitions and dependency amongst the beans based on a configuration file(XML) or the beans can be directly returned when required using Java Configuration.

Can you compare bean factory with application context?

The ApplicationContext comes with advanced features, including several that are geared towards enterprise applications, while the BeanFactory comes with only basic features. Therefore, it's generally recommended to use the ApplicationContext, and we should use BeanFactory only when memory consumption is critical.


Video Answer


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);
  }
like image 126
Ken Chan Avatar answered Oct 23 '22 13:10

Ken Chan