Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting BeanFactory into a Bean

Tags:

java

spring

I want to inject a Spring BeanFactory to a Bean created by the same BeanFactory is the any way to do so?

by the way, I'm developing a web application. If not I know that I can get the BeanFactory by having RequestContext but the bean I want to inject the BeanFactory is not in the requestContext but still in the application context. can I do that?

like image 811
hasan Avatar asked Aug 28 '13 12:08

hasan


People also ask

How do we inject into a field a bean by its name?

By using the @Autowired annotation and naming the field with the bean name.

How do you Autowire bean method?

Enabling @Autowired annotationBy declaring beans, you provide metadata to the Spring Container to return the required dependency object at runtime. This is called Spring Bean Autowiring. In java based configuration, all the bean methods are defined in the class with @configuration annotation.

Which of the given options are implementation of BeanFactory?

The most commonly used simple BeanFactory implementation is org. springframework.


2 Answers

If annotation-config mode is enabled then this should work

class Bean
   @Autowired
   BeanFactory factory;
   ...
like image 52
Evgeniy Dorofeev Avatar answered Sep 27 '22 18:09

Evgeniy Dorofeev


Your bean can implement BeanFactoryAware. By implementing this interface, your bean will receive the BeanFactory through a call to this method:

void setBeanFactory(BeanFactory beanFactory) throws BeansException

By the way, there is a similar interface (ApplicationContextAware) in order to retrieve the ApplicationContext if you need to.

like image 42
LaurentG Avatar answered Sep 27 '22 16:09

LaurentG