Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
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

Best practices and anti-patterns


So far, we have talked about using IoC containers to achieve DI, but one of the most common mistakes is to use IoC containers without doing real DI. This may sound strange, but it is a fact. Such mistakes are possible in the absence of having a proper understanding of underlying concepts.

Ideally, DI implementation should only reference the IoC container during the time of the application's startup. If a developer wraps the IoC container itself and passes it into other component to reduce any dependency, this is not a good design. Let's understand this issue with an example.

What to inject – the container itself or just dependencies?

The situation of injecting container occurs when you try to wrap the container itself either in a singleton class or a public static method to provide the dependency to other components or modules, as in the following snippet:

public class AccountService {
  //Service method.
  public void getVariablePay() {
    System.out.println...
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 £13.99/month. Cancel anytime
Visually different images