Setter-based DI

Setter-based DI is generally used for optional dependencies. In case of setter-based DI, the container first creates an instance of your bean, either by calling a no-argument constructor or static factory method. It then passes the said dependencies through each setter method. Dependencies injected through the setter method can be re-injected or changed at a later stage of application.

We will understand setter-based DI with the following code base:

public class DocumentBase {  private DocFinder docFinder; //Setter method to inject dependency.  public void setDocFinder(DocFinder docFinder) {    this.docFinder = docFinder;  }  public void performSearch() {    this.docFinder.doFind();  }}public class DocFinder { public void doFind() { ...

Get Java 9 Dependency Injection now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.