Spring Dependency Injection Explanation Use Loosely Coupled Objects

Java application is made up of a lot of objects. When the application becomes bigger and bigger, there are so many java objects in it, and many of them are tightly coupled together, this makes your application so hard to modify.

But with the Spring Framework, it is so easy to manage dependencies between all those objects. This article will show you examples of how to manage java object dependencies using the traditional method and Spring framework. You will know the benefits the Spring Framework gives to you after reading.

1. Send Email Example.

  1. Suppose we have a java interface ISendEmail like below. It has a method called sendEmail().
  2. ISendEmail.java
    package com.dev2qa.example.sendmail;
    
    public interface ISendEmail {
    	
    	public void sendEmail();
    
    }
  3. Below are two java classes that implement the above interface.
  4. SendEmailBySMTP: This class will send emails by the SMTP server.
    package com.dev2qa.example.sendmail;
    
    public class SendEmailBySMTP implements ISendEmail{
    
    	@Override
    	public void sendEmail() {
    	
    		System.out.println("Send email through SMTP.");
    	}
    }
  5. SendEmailByLDAP: This class will send emails by the LDAP server.
    package com.dev2qa.example.sendmail;
    
    public class SendEmailByLDAP implements ISendEmail {
    
    	@Override
    	public void sendEmail() {
    
    		System.out.println("Send email through LDAP. ");
    	}
    
    }
  6. Now we will show you how to call the above java object in your java code, you will find that Spring Framework can make the java object call loosely coupled extremely.

2. Call Java Object Directly.

  1. This is the most commonly used method. But if you want to send an email using the LDAP server, you have to modify, recompile and repackage the above code because the emailSender variable is tightly coupled with SendEmailBySMTP class. If there are a lot of such source codes in your application, when you want to change it, it is so complex.
    public void sendEmailDirectly()
    {
    	ISendEmail emailSender = new SendEmailBySMTP();
    	emailSender.sendEmail();
    }
    

3. Use Spring Framework.

  1. We can use Spring Framework Dependency Injection (DI) to resolve such problems easily.
  2. DI can make interface emailSender loosely coupled with the implementation class.
  3. Create a helper class SendEmailHelper
    package com.dev2qa.example.sendmail;
    
    public class SendEmailHelper {
    	
    	private ISendEmail emailSender;
    
    	public ISendEmail getEmailSender() {
    		return emailSender;
    	}
    
    	public void setEmailSender(ISendEmail emailSender) {
    		this.emailSender = emailSender;
    	}
    
    }
    
  4. Add beans in BeanSettings.xml as below. You can see SendEmailHelper class’s emailSender field refer to sendEmailBySMTP bean by XML configuration.
  5. So if you want to change emailSender to sendEmailByLDAP, you just need to change the XML configuration. Do not need to change java code.
    <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">      
           <property name="emailSender" ref="sendEmailBySMTP"></property>
    </bean>
  6. Call above java objects via Spring.
    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();
    }
  7. Below are the example Spring project structure files. You can read the article How To Install Spring IDE Eclipse Plugin to learn how to create the below project.
    D:\WORK\DEV2QA.COM-EXAMPLE-CODE\SPRINGEXAMPLEPROJECT\SRC
    └─main
        ├─java
        │  └─com
        │      └─dev2qa
        │          └─example
        │              └─spring
        │                  │
        │                  └─sendmail
        │                          ISendEmail.java
        │                          SendEmailByLDAP.java
        │                          SendEmailBySMTP.java
        │                          SendEmailClient.java
        │                          SendEmailHelper.java
        │                          SendEmailTool.java
        │
        └─resources
            │
           BeanSettings.xml
  8. ISendEmail.java

    package com.dev2qa.example.spring.sendmail;
    
    public interface ISendEmail {
        
        public void sendEmail();
    
    }
  9. SendEmailByLDAP.java

    package com.dev2qa.example.spring.sendmail;
    
    public class SendEmailByLDAP implements ISendEmail {
    
        @Override
        public void sendEmail() {
    
            System.out.println("Send email through LDAP. ");
        }
    
    }
  10. SendEmailBySMTP.java

    package com.dev2qa.example.spring.sendmail;
    
    public class SendEmailBySMTP implements ISendEmail{
    
        @Override
        public void sendEmail() {
        
            System.out.println("Send email through SMTP.");
        }
    }
  11. SendEmailClient.java

    package com.dev2qa.example.spring.sendmail;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class SendEmailClient {
    
        public static void main(String[] args) {
            
            
            SendEmailClient sec = new SendEmailClient();
            
            sec.sendEmailUseSpringFramework();
        }
    
        public void sendEmailDirectly()
        {
            ISendEmail emailSender = new SendEmailBySMTP();
            emailSender.sendEmail();
        }
        
        public void sendEmailUseSpringFramework()
        {
            /* Initiate Spring Context. */
            ApplicationContext springAppContext = new ClassPathXmlApplicationContext("AllSpringBeanSettings.xml");
    
            /* Get send email helper bean. */
            SendEmailHelper sendEmailHelper = (SendEmailHelper)springAppContext.getBean("sendEmailHelper");
    
            /* Get email sender and send email. */
            sendEmailHelper.getEmailSender().sendEmail();
            
            SendEmailTool sendEmailTool = (SendEmailTool)springAppContext.getBean("sendEmailTool");
            sendEmailTool.sendEmail();
        }
        
    }
    
  12. 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;
        }
    }
  13. 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();
        }
    }
  14. BeanSettings.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
        
        <!--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 bean -->
            <property name="emailSender" ref="sendEmailBySMTP"></property>
        </bean>
    
        <bean id="sendEmailTool" name="sendEmailTool"
            class="com.dev2qa.example.spring.sendmail.SendEmailTool">
            <constructor-arg ref="sendEmailByLDAP"></constructor-arg>
        </bean>
    </beans>

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.