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 spring bean setter method.
  2. Use spring bean’s constructor.
Bean Injection Use Setter Method

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

  1. Create an instance variable with setter method.
    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 configuration xml file. Generally the BeanSettings.xml file is located in CLASSPATH directory such as src / main / resources in Eclipse Spring project.
    BeanSettings.xml file craeted in left project tree panel
    Below example configuration xml define three bean, 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 it 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();
    	}
    
Bean Injection Use Constructor
  1. Create a java class which constructor has input parameter. Below class’s constructor has an input parameter with 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 definition in configuration xml file.
    2.1 Double click BeanSettings.xml in Eclipse left panel.
    BeanSettings.xml file craeted in left project tree panel
    2.2 Click bottom beans tab in right panel, click “New Beans…”, input id, name and choose class SendEmailTool. Click Next button. add bean in configuration xml file
    2.3 Choose Constructor Args in next dialog, add constructor parameter reference.
    add spring bean constructor parameter reference
  3. 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>
  4. Invoke above spring bean.
    	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();
    	}
    
Setter Injection vs Constructor Injection

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

READ :   Use util:constant To Declare Final Static Field As Spring Bean

Source Code

Download “SpringExampleProject-1.zip” SpringExampleProject-1.zip – Downloaded 48 times – 22 KB

(Visited 390 times, 1 visits today)

Leave a Reply

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.