Auto-wiring by type

In this mode, Spring does binding of beans based on type. Here, the type means the class attribute of <bean>Spring looks for the bean with the same type as the property that needs to be autowired. In other words, dependencies are auto bound with the bean having the same type.

If more than one bean of the same type exists, Spring shows exception. If Spring doesn't find the bean with a matching type, nothing happens; simply, the property will not be set. Let's understand this by looking at the following example:

public class EmailService {
public void sendEmail() {
System.out.println(" Sending Email ..!! ");
}
}

public class HRService {
private EmailService emailService = null;
//Setter DI method.
public void setEmailService(EmailService emailService) {
this.emailService = emailService;
}

public void initiateSeparation() {
//Business logic for sepration process

if(emailService !=null) {
emailService.sendEmail();
}
}
}

In the preceding code, HRService depends on EmailService. HRService has a setter method through which Spring will inject the dependency of EmailService. Previous scenarios can be configured in Spring as follows:

<!-- Example of autowire byType -->
<bean id="emailService" class="com.packet.spring.autowire.di.EmailService">
</bean>
<bean id="hrService" class="com.packet.spring.autowire.di.HRService" autowire="byType">
</bean>

When Spring reads the autowire="byType" attribute in the hrService bean, it will try to search the bean with the same type as the property of hrService. Spring expects just one such bean. If found, it will inject that bean. 

Since this is autowire by type, Spring relies on the type of property to inject the dependency, and not on the name of the setter method. Spring only expects that the method should take the reference of dependency as a parameter to set it with the property of the bean.
..................Content has been hidden....................

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