Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Java 9 Dependency Injection

You're reading from   Java 9 Dependency Injection Write loosely coupled code with Spring 5 and Guice

Arrow left icon
Product type Paperback
Published in Apr 2018
Publisher Packt
ISBN-13 9781788296250
Length 246 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Nilang Patel Nilang Patel
Author Profile Icon Nilang Patel
Nilang Patel
Krunal Patel Krunal Patel
Author Profile Icon Krunal Patel
Krunal Patel
Arrow right icon
View More author details
Toc

Injection using the setter method versus the constructor


There are two straightforward options of DI – setter- or constructor-based DI. Both of these methods perform the same operation—injecting dependencies—but at different times of the object's lifespan. One happens during object instantiation, while the other happens on calling the setter method explicitly.

A very obvious dilemma comes into the picture when you implement DI with these two options. Understanding the difference is important because it reflects the basic problem of the object-oriented programming context: do we initiate the field variable with the constructor argument or through the setter method?

Constructor-based DI

Passing dependencies with a constructor is more clear in terms of describing what is required to create an object. You may write multiple versions of constructors, each taking a different combination of dependency objects, if that is allowed.

Alongside initializing fields with the constructor, you can hide them...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image