Spring Bean Dependency Injection Methods Comparison – Setter Vs Constructor

In Spring Framework, there are two methods that you can use to achieve spring bean Dependency Injection ( DI ).

  1. Use the spring bean setter method.
  2. Use the spring bean’s constructor.

1. Bean Injection Use Setter Method.

This is the most commonly used bean dependency injection method. You just need to do the following.

  1. Create an instance variable with the setter method in the spring bean java class as below.
    SendEmailHelper.java

    package com.dev2qa.example.spring.sendmail;
    
    public class SendEmailHelper {
    	
    	/* This is the instance variable. */
    	private ISendEmail emailSender;
    
    	/* This method is used to inject object to emailSender(instance variable). */
    	public void setEmailSender(ISendEmail emailSender) {
    		this.emailSender = emailSender;
    	}
    
    	public ISendEmail getEmailSender() {
    		return emailSender;
    	}
    }
    
  2. Add bean definition in the configuration XML file. Generally, the BeanSettings.xml file is located in the CLASSPATH directory such as src / main / resources in the Eclipse Spring project. Below example configuration XML defines three beans, the first two will be injected by the third use setter method.
    <!--Below two beans all implement ISendEmail interface. -->
    <bean id="sendEmailBySMTP" class="com.dev2qa.example.spring.sendmail.SendEmailBySMTP"> </bean> 
    <bean id="sendEmailByLDAP" class="com.dev2qa.example.spring.sendmail.SendEmailByLDAP"> </bean> 
    
    <bean id="sendEmailHelper" class="com.dev2qa.example.spring.sendmail.SendEmailHelper"> 
            <!-- Below property refer to the above sendEmailBySMTP -->       
            <property name="emailSender" ref="sendEmailBySMTP"></property> 
    </bean>
  3. Invoke the spring bean in java code.
    SendEmailClient.java

    public void sendEmailUseSpringFramework()
    {
    	/* Initiate Spring Context. */
    	ApplicationContext springAppContext = new ClassPathXmlApplicationContext("BeanSettings.xml");
    
    	/* Get send email helper bean. */
    	SendEmailHelper sendEmailHelper = (SendEmailHelper)springAppContext.getBean("sendEmailHelper");
    
    	/* Get email sender and send email. */
    	sendEmailHelper.getEmailSender().sendEmail();
    }
    

2. Bean Injection Use Constructor.

  1. Create a java class with the constructor has input parameters. Below class’s constructor has an input parameter with the type ISendEmail.
    SendEmailTool.java

    package com.dev2qa.example.spring.sendmail;
    
    public class SendEmailTool {
    	
    	/* This is the instance variable. */
    	private ISendEmail emailSender;
    
    	/* Create constructor with input parameter. */
    	public SendEmailTool(ISendEmail emailSender) {
    		this.emailSender = emailSender;
    	}
    	
    	/* This is the business logic method which will send email. */
    	public void sendEmail()
    	{
    		/* Call injected instance variable's sendEmail() method. */
    		this.emailSender.sendEmail();
    	}
    }
    
  2. Use Eclipse spring bean editor to add definitions in the configuration XML file follow the below steps.
  3. Double click BeanSettings.xml in Eclipse left panel.
  4. Click the bottom beans tab in the Eclipse right panel, click the New Beans… button to open the Create New Bean dialog.
  5. Input bean Id ( sendEmailTool ), Name ( sendEmailTool ), and browse to choose the Class com.dev2qa.example.spring.sendmail.SendEmailTool. Click the Next button.
  6. Now it will show the Properties and Constructor Parameters dialog. Add or edit constructor parameters reference in the Constructor Args section.
  7. Now you can see the XML configuration has been changed to below.
    <bean id="sendEmailByLDAP" class="com.dev2qa.example.spring.sendmail.SendEmailByLDAP"> </bean>
    
    <bean id="sendEmailTool" name="sendEmailTool" class="com.dev2qa.example.spring.sendmail.SendEmailTool"> 
           <constructor-arg ref="sendEmailByLDAP"></constructor-arg> 
    </bean>
  8. You can invoke the above spring bean in your java source code like below.
    public void sendEmailUseSpringFramework()
    {
    	/* Initiate Spring Context. */
    	ApplicationContext springAppContext = new ClassPathXmlApplicationContext("BeanSettings.xml");
                   
            /* Get SendEmailTool bean use constructor parameter. */
    	SendEmailTool sendEmailTool = (SendEmailTool)springAppContext.getBean("sendEmailTool");
    		
            /* Call it's business logic method.*/  
            sendEmailTool.sendEmail();
    }
    

3. Setter Injection vs Constructor Injection.

  1. All the above methods are ok for bean dependency injection. You can use it as you need and fit your requirements. But use the setter method to implement spring bean injection is a more popular method in most cases.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.