0

I am a newbie in Spring Framework and I came across the below POJO beans:

@Component
Class A{

@Autowired
B b;

}

@Component
Class B{
// primitive variables
}

My doubt is what will be the order of initialisation and injection of beans? Will it be:

  1. Instance of A is created(Constructor is called of A)
  2. Instance of B is created(Constructor is called of B)
  3. B is injected into A

OR

  1. Instance of B is created(Constructor is called of B)
  2. Instance of A is created(Constructor is called of A)
  3. B is injected into A
ghostrider
  • 2,046
  • 3
  • 23
  • 46
  • Could be either. – M. Deinum Apr 12 '18 at 12:03
  • Why do you care? – lexicore Apr 12 '18 at 12:03
  • 1
    It doesn't matter, since it is like setter based, which is not mandatory at the time of instantiation. So, container can decide in which order it needs to instantiate it. – Avinash Anand Apr 12 '18 at 12:08
  • 4
    actually it is field injection not setter injection. – M. Deinum Apr 12 '18 at 12:10
  • @AvinashAnand what if we injected B using a constructor injection? What will be the order then? – ghostrider Apr 12 '18 at 12:18
  • 1
    @ghostrider - then Instance of B would be needed before instantiating A. Hence, spring would try to instantiate the dependency first and then the actual bean which is dependent on the injections. please refer spring docs for more - https://docs.spring.io/spring/docs/4.3.16.RELEASE/spring-framework-reference/htmlsingle/#beans-dependency-resolution – Avinash Anand Apr 12 '18 at 12:28
  • @M.Deinum - Thanks for correcting me. It is a field injection. – Avinash Anand Apr 12 '18 at 12:29
  • 1
    See https://stackoverflow.com/questions/39890849/what-exactly-is-field-injection-and-how-to-avoid-it which will describe the types of injection in a really nice way. – MuratOzkan Apr 12 '18 at 12:29
  • 1
    note: you can actually tell spring the order of bean instantiation with [`@DependsOn`](https://www.logicbig.com/tutorials/spring-framework/spring-core/using-depends-on.html) – Sharon Ben Asher Apr 12 '18 at 12:31

0 Answers0