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?
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.
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With