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() {
System.out.println(" Finding in Document Base ");
}
}

public class DIWithSetterCheck {
public static void main(String[] args) {
ApplicationContext springContext = new ClassPathXmlApplicationContext("application-context.xml");
DocumentBase docBase = (DocumentBase) springContext.getBean("docBase");
docBase.performSearch();
}
}

The  DocumentBase class depends on DocFinder, and we are passing it through the setter method. You need to define the configuration metadata for Spring, as per the following snippet:

    <bean id="docBase" class="com.packet.spring.setter.di.DocumentBase">
<property name="docFinder" ref="docFinder" />
</bean>

<bean id="docFinder" class="com.packet.spring.setter.di.DocFinder">
</bean>

Setter-based DI can be defined through the <property> element under <bean>. The name attribute denotes the name of the setter name. In our case, the name attribute of the property element is docFinder, so Spring will call the setDocFinder method to inject the dependency. The pattern to find the setter method is to prepend set and make the first character capital.

The name attribute of the <property> element is case-sensitive. So, if you set the name to docfinder, Spring will try to call the setDocfinder method and will show an error.

Just like constructor DI, Setter DI also supports supplying the value for primitives, as per the following snippet:

<bean id="docBase" class="com.packet.spring.setter.di.DocumentBase">
<property name="buildNo" value="1.2.6" />
</bean>

Since the setter method takes only one argument, there is no scope of argument ambiguity. Whatever value you are passing here, Spring will convert it to an actual primitive type of the setter method parameter. If it's not compatible, it will show an error. 

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

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