0

Here is an example of what i want to understand :

@Component
class Foo {
   
   @Autowired B b; // B is @Component
   @Autowired C c; // C is @Component
   @Autowired A a; // A is @Component

}

What is the ordering that spring takes for injecting A, B and C beans in Foo bean :

  1. It starts with B beacause it is the first declared ?
  2. It starts with A because by default it is the first in alphabetical order ?
  3. It injects beans randomly ?

I understand that @Autowired is not recommanded and we should use constructor for dependency injection instead but just i want to know how spring behaves by default.

Thanks

Chicov
  • 19
  • 5
  • 1
    Depends really on the spring internals. I.e. if the fields are stored in ordered/sorted collections or in unordered/unsorted ones. – Lino Feb 03 '22 at 11:45
  • 1
    There is no garantueed ordering. Spring uses reflection to obtain the autowired fields, so it depends on the actual underlying implementation on reflection in which order those fields are being returned. – M. Deinum Feb 03 '22 at 12:34
  • Thanks for your replies, So if i understand, when i launch my web application two times, then the ordering will not be necessary the same for each restart ? – Chicov Feb 03 '22 at 13:38
  • 2
    The order of injection can differ, the fields in your class will still be the same. Although when running in the same JVM and underlying system it probably will be the same. – M. Deinum Feb 03 '22 at 13:54
  • 1
    See also: https://stackoverflow.com/questions/22760615 – Stephen C Feb 03 '22 at 14:29
  • @Deinum Yes, it seems to be logic because my problem was that my application launches perfectly in local but not in a DEV pod. – Chicov Feb 04 '22 at 10:16

0 Answers0