How to code DI
Have a look at the following example. CartService
has a dependency on CartRepository
. The CartRepository
instantiation is done inside the CartService
constructor:
public class CartService { private CartRepository repository; public CartService() { this.repository = new CartRepositoryImpl(); } }
We can decouple this dependency in the following way:
public class CartService { private CartRepository repository; public CartService(CartRepository repository) { this.repository = repository; } }
If you create a bean of the CartRepository
implementation, you can easily inject the CartRepository
bean using configuration metadata. Before that, let’s have a look at the Spring container again.
You have seen how ApplicationContext
can be initialized in the The @Import annotation subsection of this chapter. When it gets created, it takes all the...