application, but it adds complexity in the additional code required to couple these components back
together in order to perform any useful tasks.
Setter Injection vs. Constructor Injection
Now that we have established which method of IoC is preferable, you still need to choose whether to use
Setter Injection or Constructor Injection. Constructor Injection is particularly useful when you
absolutely must have an instance of the dependency class before your component is used. Many
containers, Spring included, provide a mechanism for ensuring that all dependencies are defined when
you use Setter Injection, but by using Constructor Injection, you assert the requirement for the
dependency in a container-agnostic manner.
Setter Injection is useful in a variety of cases. If the component is exposing its dependencies to the
container but is happy to provide its own defaults, then Setter Injection is usually the best way to
accomplish this. Another benefit of Setter Injection is that it allows dependencies to be declared on an
interface, although this is not as useful as you might first think. Consider a typical business interface
with one business method, defineMeaningOfLife(). If, in addition to this method, you define a setter for
injection such as setEncylopedia(), then you are mandating that all implementations must use or at
least be aware of the encyclopedia dependency. However, you don't need to define setEncylopedia() in
the business interface. Instead, you can define the method in the classes implementing the business
interface. While programming in this way, all recent IoC containers, Spring included, can work with the
component in terms of the business interface but still provide the dependencies of the implementing
class. An example of this may clarify this matter slightly. Consider the business interface in Listing 4-7.
Listing 4-7. The Oracle Interface
package com.apress.prospring3.ch4;
public interface Oracle {
public String defineMeaningOfLife();
}
Notice that the business interface does not define any setters for Dependency Injection. This
interface could be implemented as shown in Listing 4-8.
Listing 4-8. Implementing the Oracle Interface
package com.apress.prospring3.ch4;
public class BookwormOracle implements Oracle {
private Encyclopedia encyclopedia;
public void setEncyclopedia(Encyclopedia encyclopedia) {
this. encyclopedia = encyclopedia;
}
public String defineMeaningOfLife() {
return "Encyclopedias are a waste of money - use the Internet";
}
}
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home