2

In several code examples I see autowiring used instead of constructor injection. Can any one explain why Constructor injection is difficult but autowiring is possible on spring configuration classes? Thanks in advance.

this question does touch the topic but doesn't have the detailed answer.

Vishal Maral
  • 1,279
  • 1
  • 10
  • 30
  • Can you extend your question about *Constructor injection is difficult*? – Ori Marko Nov 22 '18 at 11:30
  • Please refer the link provided in the question. it mentions 'earlier versions don't support', 'possible for simple cases only', 'problem when using this feature' – Vishal Maral Nov 22 '18 at 12:26
  • 1
    The answer is yes.Btw,I use @Autowired cause it's simple and convenient.After I adding or taking away some fields,I dont need to change the constructor.Further more,with lombok I dont need to write constructor,getter or setter by myself,so I choose field injection. – AokoQin Nov 23 '18 at 03:28

1 Answers1

0

Constructor injection requires all dependencies are available beforehand.

In early Spring Boot (before 2.6) circular dependencies are allowed by default. It is impossible to have circular bean dependencies together with the constructor injection (egg-chicken problem if A => B & B => A and both use it).

I think for this reason such expression of DI dependencies was implemented later. With a default constructor + setter or @Autowired you could resolve circular dependencies.

gavenkoa
  • 45,285
  • 19
  • 251
  • 303