Announcement Announcement Module
Collapse
No announcement yet.
How Autowiring of Fields actually happen? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • How Autowiring of Fields actually happen?

    Hi,

    Spring supports constructor and setter injection.

    Now I am wondering that if we annotiate private fields with @Autowired annotation and we don't provide appropriate constructor and any setter method for the same, still autowiring happens.

    Can please someone explain how exactly spring achieves this?

    Regards,
    Jubin

  • #2
    Just was thinking and I came up with the following :

    A Spring bean is instantiated only with setter injection or constructor injection. Till this point the field (annotiated with @Autowired) is null.
    But during BeanPostProcessor stage, Spring injects the Autowired bean by type....

    Is this correct?

    Comment


    • #3
      The explanation I thought satisfy for @Required annotation but not for @Autowired.

      The reason is BeanPostProcessor comes into play once the bean is created. Now @Autowired supports constructor injection. And constructor gets invoked during the bean creation time. Now how can BeanPostProcessor perform constructor injection?

      Please anyone can explain clearly....??

      Thanks,
      Jubin

      Comment


      • #4
        Sorry Andrew, my explanation satisfy only for @Required but it doesn't seem fine with @Autowired...... Hope we get an appropriate answer..........

        Comment


        • #5
          The AutowiredAnnotationBeanPostProcessor is indeed a BeanPostProcessor. However it is a special type of BeanPostProcessor, to be precise it is an instance of the InstantiationAwareBeanPostProcessor.

          This one kicks in before the object is instantiated and finds the constructors and matches the constructor arguments to the beans available in the applicationcontext.

          Comment


          • #6
            Thanks Marten, this certainly helps in clearing my doubt and satisfy me.

            Just I wonder why this task was not given to an BeanFactoryPostProcessor (instead of BeanPostProcessor) in order to maintain the consistency for all the roles...?

            Thanks,
            Jubin

            Comment

            Working...
            X