Home > Net >  Where does the dependency injection take place?
Where does the dependency injection take place?

Time:01-29

As far as i know:

  1. BeanFactory creates beans according to its definitions.
  2. Then sends it to BeanPostProcessor to invoke postProcessBeforeInitialization().
  3. Receives it back and provides init() method.
  4. BeanPostProcessor with postProcessAfterInitialization() method.
  5. Bean finally configured and sent into IoC container.

My question is: "At what stage does dependency injection take place?".

Really curious on how it works under the hood.

CodePudding user response:

Dependency injection typically takes place during the initialization of a bean, after the bean has been instantiated by the BeanFactory, but before the bean is fully initialized and ready to be used by the application.

The process typically works as follows:

The BeanFactory creates an instance of the bean according to its definitions. The BeanPostProcessor's postProcessBeforeInitialization() method is invoked, which allows for any pre-initialization processing to take place, such as setting up some initial values or performing some other setup tasks. The BeanFactory then proceeds to set the bean's properties and dependencies, using either setter injection or constructor injection, which are the two most common forms of dependency injection. This step is where the actual injection of dependencies takes place. The BeanPostProcessor's postProcessAfterInitialization() method is invoked, which allows for any post-initialization processing to take place, such as performing some validation or other tasks on the fully initialized bean. The Bean is finally configured and sent into IoC container. It's important to note that the step 2 and 4 are optional, and not all BeanPostProcessor implementation will invoke them.

BeanPostProcessor is an interface that allows for additional processing to be done on bean instances before and after their initialization. It is useful for performing custom logic on beans during the initialization process, but it is not necessary for dependency injection to take place.

  • Related