Dependency injection

Spring MVC is a part of the overall Spring Framework. The core feature of the Spring Framework is dependency injection (DI). Almost all other features of the Spring Framework use DI. Objects managed by the dependency injection framework are not directly instantiated in the code (using, for example, the new operator). Let's call them managed objects. These objects are created by a DI framework, such as Spring. Because these objects are created by a framework, the framework has a lot more flexibility in deciding how to set values in the object and from where to get them. For example, your Data Access Object (DAO) class might need an instance of a database connection factory object. However, instead of instantiating it in the DAO class, you just tell the DI framework that when it instantiates the DAO, it has to set the value of a member variable for the connection pool factory. Of course, the parameters for the connection pool factory will have to be configured somewhere and be known to the DI framework.

When a class instantiates another class, there is tight dependency between them. Such design could be a problem if you want to test classes independently of others. For example, you may want to test a class that has business logic, but one that also refers to a DAO, which in turn depends on a JDBC connection object. When testing the first class, you will have to instantiate the DAO and configure the connection pool. As we saw in Chapter 5, Unit Testing, unit tests should be able to run without any external dependencies. One way to achieve this is by using DI. Instead of instantiating the DAO class, our class could refer to an interface that is implemented by the DAO and have the DI framework inject the implementation of this interface at runtime. When you are unit testing this class, the DI framework can be configured to inject a mock object that implements the required interface. Thus, DI enables loose coupling between objects.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.237.201