benny
benny

Reputation: 291

What are the advantages of constructor autowiring over normal autowiring or property autowiring?

Is there any specific advantages for constructor autowiring over property autowiring ... Or normal one .? Superior forcing team to use constructor autowiring in spring boot .. is there any specific advantages for it . Pros and cons of both type of autowiring

Upvotes: 3

Views: 7393

Answers (2)

Gaurav Misra
Gaurav Misra

Reputation: 19

Constructor wiring is also helpful in writing bugfree code. If you wire dependencies through constructor autowiring, you would be able to easily mock them using mocking frameworks, and inject them through the constructor.

Specifically, Mockito fails silently while mocking dependencies, and if you haven't used constructor autowiring it becomes hard to debug where your code is breaking.

If you follow TDD for writing big enterprise applications, constructor autowiring is helpful.

Upvotes: 1

olambert
olambert

Reputation: 1115

Constructor autowiring has advantages in that you can make the wired in fields final (particularly useful if your bean will be called from multiple threads as threadsafety is easier to analyse with finals). And you can ensure that the bean is always constructed in a valid way (although you can always implement InitializingBean and use the afterPropertiesSet method to achieve the same if you're wiring in properties).

Wiring properties can be better if you have many fields as it avoids having very many arguments in your constructor, and wiring by name is less prone to mixing up the variables if you're using xml (consider a constructor with many arguments all of one type - it would be easy to wire in the wrong variable). Wiring properties also makes it easier to have optional properties - optional properties with constructor wiring would require multiple constructors, which can quickly get complicated.

In summary, both approaches have their pros and cons - we usually use property wiring unless there's a particular reason we should use constructor wiring.

Upvotes: 4

Related Questions