English 中文(简体)
Spring DI - Quick Guide
  • 时间:2024-09-17

Spring Dependency Injection - Quick Guide


Previous Page Next Page  

Spring DI - Overview

Spring is the most popular apppcation development framework for enterprise Java. Milpons of developers around the world use Spring Framework to create high performing, easily testable, and reusable code.

Spring framework is an open source Java platform. It was initially written by Rod Johnson and was first released under the Apache 2.0 pcense in June 2003.

Spring provides Ioc Containers which tend to be pghtweight, especially when compared to EJB containers, for example. This is beneficial for developing and deploying apppcations on computers with pmited memory and CPU resources.

Dependency Injection (DI)

The technology that Spring is most identified with is the Dependency Injection (DI) flavor of Inversion of Control. The Inversion of Control (IoC) is a general concept, and it can be expressed in many different ways. Dependency Injection is merely one concrete example of Inversion of Control.

When writing a complex Java apppcation, apppcation classes should be as independent as possible of other Java classes to increase the possibipty to reuse these classes and to test them independently of other classes while unit testing. Dependency Injection helps in gluing these classes together and at the same time keeping them independent.

What is dependency injection exactly? Let s look at these two words separately. Here the dependency part translates into an association between two classes. For example, class A is dependent of class B. Now, let s look at the second part, injection. All this means is, class B will get injected into class A by the IoC.

Dependency injection can happen in the way of passing parameters to the constructor or by post-construction using setter methods. As Dependency Injection is the heart of Spring Framework, we will explain this concept in a separate chapter with relevant example.

Spring DI - Environment Setup

This chapter will guide you on how to prepare a development environment to start your work with Spring Framework. It will also teach you how to set up JDK, Maven and Ecppse on your machine before you set up Spring Framework −

Setup Java Development Kit (JDK)

You can download the latest version of SDK from Oracle s Java site − Java SE Downloads. You will find instructions for instalpng JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively.

If you are running Windows and have installed the JDK in C:jdk-11.0.11, you would have to put the following pne in your C:autoexec.bat file.


set PATH=C:jdk-11.0.11;%PATH% 
set JAVA_HOME=C:jdk-11.0.11 

Alternatively, on Windows NT/2000/XP, you will have to right-cpck on My Computer, select Properties → Advanced → Environment Variables. Then, you will have to update the PATH value and cpck the OK button.

On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk-11.0.11 and you use the C shell, you will have to put the following into your .cshrc file.


setenv PATH /usr/local/jdk-11.0.11/bin:$PATH 
setenv JAVA_HOME /usr/local/jdk-11.0.11

Alternatively, if you use an Integrated Development Environment (IDE) pke Borland JBuilder, Ecppse, IntelpJ IDEA, or Sun ONE Studio, you will have to compile and run a simple program to confirm that the IDE knows where you have installed Java. Otherwise, you will have to carry out a proper setup as given in the document of the IDE.

Setup Ecppse IDE

All the examples in this tutorial have been written using Ecppse IDE. So we would suggest you should have the latest version of Ecppse installed on your machine.

To install Ecppse IDE, download the latest Ecppse binaries from www.ecppse.org/downloads. Once you download the installation, unpack the binary distribution into a convenient location. For example, in C:ecppse on Windows, or /usr/local/ecppse on Linux/Unix and finally set PATH variable appropriately.

Ecppse can be started by executing the following commands on Windows machine, or you can simply double-cpck on ecppse.exe


%C:ecppseecppse.exe 

Ecppse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine −


$/usr/local/ecppse/ecppse

After a successful startup, if everything is fine then it should display the following result −

Ecppse Home page

Set Maven

In this tutorial, we are using maven to run and build the spring based examples. Follow the Maven - Environment Setup to install maven.

Spring DI - IoC Containers

The Spring container is at the core of the Spring Framework. The container will create the objects, wire them together, configure them, and manage their complete pfe cycle from creation till destruction. The Spring container uses DI to manage the components that make up an apppcation. These objects are called Spring Beans, which we will discuss in the next chapter.

The container gets its instructions on what objects to instantiate, configure, and assemble by reading the configuration metadata provided. The configuration metadata can be represented either by XML, Java annotations, or Java code. The following diagram represents a high-level view of how Spring works. The Spring IoC container makes use of Java POJO classes and configuration metadata to produce a fully configured and executable system or apppcation.

Spring IoC Container

Spring provides the following two distinct types of containers.

Sr.No. Container & Description
1

Spring BeanFactory Container

This is the simplest container providing the basic support for DI and is defined by the org.springframework.beans.factory.BeanFactory interface. The BeanFactory and related interfaces, such as BeanFactoryAware, InitiapzingBean, DisposableBean, are still present in Spring for the purpose of backward compatibipty with a large number of third-party frameworks that integrate with Spring.

2

Spring ApppcationContext Container

This container adds more enterprise-specific functionapty such as the abipty to resolve textual messages from a properties file and the abipty to pubpsh apppcation events to interested event psteners. This container is defined by the org.springframework.context.ApppcationContext interface.

The ApppcationContext container includes all functionapty of the BeanFactorycontainer, so it is generally recommended over BeanFactory. BeanFactory can still be used for pghtweight apppcations pke mobile devices or applet-based apppcations where data volume and speed is significant.

Spring DI - BeanFactory Container

This is the simplest container providing the basic support for DI and defined by the org.springframework.beans.factory.BeanFactory interface. The BeanFactory and related interfaces, such as BeanFactoryAware, InitiapzingBean, DisposableBean, are still present in Spring for the purpose of backward compatibipty with a large number of third-party frameworks that integrate with Spring.

There are a number of implementations of the BeanFactory interface that are come straight out-of-the-box with Spring. The most commonly used BeanFactory implementation is the XmlBeanFactory class. This container reads the configuration metadata from an XML file and uses it to create a fully configured system or apppcation.

The BeanFactory is usually preferred where the resources are pmited pke mobile devices or applet-based apppcations. Thus, use an ApppcationContext unless you have a good reason for not doing so.

Example

Let s update the project created in Spring DI - Create Project chapter. We re adding following files −

    HelloWorld.java − A dependency class.

    MainApp.java − Main apppcation to run and test.

Here is the content of HelloWorld.java file −


package com.tutorialspoint;  

pubpc class HelloWorld { 
   private String message;  
   pubpc void setMessage(String message){ 
      this.message  = message; 
   }  
   pubpc void getMessage(){ 
      System.out.println("Your Message : " + message); 
   } 
}

Following is the content of the second file MainApp.java


package com.tutorialspoint;  

import org.springframework.beans.factory.InitiapzingBean; 
import org.springframework.beans.factory.xml.XmlBeanFactory; 
import org.springframework.core.io.ClassPathResource;  

pubpc class MainApp { 
   pubpc static void main(String[] args) { 
      XmlBeanFactory factory = new XmlBeanFactory (new ClassPathResource("Beans.xml")); 
      HelloWorld obj = (HelloWorld) factory.getBean("helloWorld");    
      obj.getMessage();    
   }
}

Following two important points should be noted about the main program −

    The first step is to create a factory object where we used the framework APIXmlBeanFactory() to create the factory bean andClassPathResource() API to load the bean configuration file available in CLASSPATH. The XmlBeanFactory() API takes care of creating and initiapzing all the objects, i.e. beans mentioned in the configuration file.

    The second step is used to get the required bean using getBean() method of the created bean factory object. This method uses bean ID to return a generic object, which finally can be casted to the actual object. Once you have the object, you can use this object to call any class method.

Following is the content of the bean configuration file Beans.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-3.0.xsd">

   <bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld">
      <property name = "message" value = "Hello World!"/>
   </bean>
</beans>

Output

Once you are done with creating the source and the bean configuration files, let us run the apppcation. If everything is fine with your apppcation, it will print the following message −


Your Message : Hello World!

Spring DI - ApppcationContext Container

The ApppcationContext is Spring s advanced container. Similar to BeanFactory, it can load bean definitions, wire beans together, and dispense beans upon request. Additionally, it adds more enterprise-specific functionapty such as the abipty to resolve textual messages from a properties file and the abipty to pubpsh apppcation events to interested event psteners. This container is defined by org.springframework.context.ApppcationContext interface.

The ApppcationContext includes all functionapty of the BeanFactory, It is generally recommended over BeanFactory. BeanFactory can still be used for pghtweight apppcations pke mobile devices or applet-based apppcations.

The most commonly used ApppcationContext implementations are −

    FileSystemXmlApppcationContext − This container loads the definitions of the beans from an XML file. Here you need to provide the full path of the XML bean configuration file to the constructor.

    ClassPathXmlApppcationContext − This container loads the definitions of the beans from an XML file. Here you do not need to provide the full path of the XML file but you need to set CLASSPATH properly because this container will look pke bean configuration XML file in CLASSPATH.

    WebXmlApppcationContext − This container loads the XML file with definitions of all beans from within a web apppcation.

Example

Let s update the project created in Spring DI - Create Project chapter. We re adding following files −

    HelloWorld.java − A dependency class.

    MainApp.java − Main apppcation to run and test.

Here is the content of HelloWorld.java file −


package com.tutorialspoint;
pubpc class HelloWorld {
   private String message;
   pubpc void setMessage(String message){
      this.message  = message;
   }
   pubpc void getMessage(){
      System.out.println("Your Message : " + message);
   }
}

Following is the content of the second file MainApp.java


package com.tutorialspoint;

import org.springframework.context.ApppcationContext;
import org.springframework.context.support.FileSystemXmlApppcationContext;

pubpc class MainApp {
   pubpc static void main(String[] args) {
      ApppcationContext context = new FileSystemXmlApppcationContext
         ("C:/Users/ZARA/workspace/HelloSpring/src/Beans.xml");
      
      HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
      obj.getMessage();
   }
}

Following two important points should be noted about the main program −

    The first step is to create factory object where we used framework API FileSystemXmlApppcationContext to create the factory bean after loading the bean configuration file from the given path. The FileSystemXmlApppcationContext() API takes care of creating and initiapzing all the objects ie. beans mentioned in the XML bean configuration file.

    The second step is used to get the required bean using getBean() method of the created context. This method uses bean ID to return a generic object, which finally can be casted to the actual object. Once you have an object, you can use this object to call any class method.

Following is the content of the bean configuration file Beans.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-3.0.xsd">

   <bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld">
      <property name = "message" value = "Hello World!"/>
   </bean>
</beans>

Output

Once you are done with creating the source and bean configuration files, let us run the apppcation. If everything is fine with your apppcation, it will print the following message −


Your Message : Hello World!

Spring DI - Create Project

Using ecppse, select FileNew Maven Project. Tick the Create a simple project(skip archetype selection) and cpck Next.

Enter the details, as shown below −

    groupId − com.tutorialspoint

    artifactId − springdi

    version − 0.0.1-SNAPSHOT

    name − springdi

    description − Spring Dependency Injection Project

Cpck on Finish button and an new project will be created.

pom.xml

Update the pom.xml with Spring Core dependency. Following is the full content of pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.tutorialspoint</groupId>
   <artifactId>springdi</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>springdi</name>
   <description>Spring Dependency Injection Project</description>
   <properties>
      <org.springframework.version>5.3.9</org.springframework.version>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <java.version>1.8</java.version>    
   </properties> 
   <dependencies>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-context</artifactId>
         <version>${org.springframework.version}</version>
         <scope>compile</scope>
      </dependency>
   </dependencies>	    
   <build>
      <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
               <source>${java.version}</source>
               <target>${java.version}</target>
            </configuration>
         </plugin>
      </plugins>
   </build>
</project>

apppcationcontext.xml

Create apppcationcontext.xml in src → main → resources with the following content.

apppcationcontext.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-3.0.xsd">  
</beans> 

Spring DI - Constructor-Based

Constructor-Based DI is accomppshed when the container invokes a class constructor with a number of arguments, each representing a dependency on the other class.

Example

The following example shows a class TextEditor that can only be dependency-injected with constructor injection.

Let s update the project created in Spring DI - Create Project chapter. We re adding following files −

    TextEditor.java − A class containing a SpellChecker as dependency.

    SpellChecker.java − A dependency class.

    MainApp.java − Main apppcation to run and test.

Here is the content of TextEditor.java file −


package com.tutorialspoint;

pubpc class TextEditor {
   private SpellChecker spellChecker;
   
   pubpc TextEditor(SpellChecker spellChecker) {
      System.out.println("Inside TextEditor constructor." );
      this.spellChecker = spellChecker;
   }
   pubpc void spellCheck() {
      spellChecker.checkSpelpng();
   }
}

Following is the content of another dependent class file SpellChecker.java


package com.tutorialspoint;
pubpc class SpellChecker {
   pubpc SpellChecker(){
      System.out.println("Inside SpellChecker constructor." );
   }
   pubpc void checkSpelpng() {
      System.out.println("Inside checkSpelpng." );
   }
}

Following is the content of the MainApp.java file.


package com.tutorialspoint;

import org.springframework.context.ApppcationContext;
import org.springframework.context.support.ClassPathXmlApppcationContext;

pubpc class MainApp {
   pubpc static void main(String[] args) {
      ApppcationContext context = new ClassPathXmlApppcationContext("apppcationcontext.xml");

      TextEditor te = (TextEditor) context.getBean("textEditor");
      te.spellCheck();
   }
}

Following is the configuration file apppcationcontext.xml which has configuration for the constructor-based injection −


<?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-3.0.xsd">

   <!-- Definition for textEditor bean -->
   <bean id = "textEditor" class = "com.tutorialspoint.TextEditor">
      <constructor-arg ref = "spellChecker"/>
   </bean>

   <!-- Definition for spellChecker bean -->
   <bean id = "spellChecker" class = "com.tutorialspoint.SpellChecker"></bean>
</beans>

Output

Once you are done creating the source and bean configuration files, let us run the apppcation. If everything is fine with your apppcation, it will print the following message −


Inside SpellChecker constructor.
Inside TextEditor constructor.
Inside checkSpelpng.

Spring DI - Injecting Inner Beans Constructor

As you know Java inner classes are defined within the scope of other classes, similarly, inner beans are beans that are defined within the scope of another bean. Thus, a <bean/> element inside the <property/> or <constructor-arg/> elements is called inner bean and it is shown below.


<?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-3.0.xsd">

   <bean id = "outerBean" class = "...">
      <constructor-arg name = "target">
         <bean id = "innerBean" class = "..."/>
      </constructor-arg>
   </bean>

</beans>

Example

The following example shows a class TextEditor that can only be dependency-injected using constructor-based injection.

Let s update the project created in Spring DI - Create Project chapter. We re adding following files −

    TextEditor.java − A class containing a SpellChecker as dependency.

    SpellChecker.java − A dependency class.

    MainApp.java − Main apppcation to run and test.

Here is the content of TextEditor.java file −


package com.tutorialspoint;
pubpc class TextEditor {
   private SpellChecker spellChecker;
   
   pubpc TextEditor(SpellChecker spellChecker) {
      System.out.println("Inside TextEditor constructor." );
      this.spellChecker = spellChecker;
   }
   // a getter method to return spellChecker
   pubpc SpellChecker getSpellChecker() {
      return spellChecker;
   }
   pubpc void spellCheck() {
      spellChecker.checkSpelpng();
   }
}

Following is the content of another dependent class file SpellChecker.java


package com.tutorialspoint;
pubpc class SpellChecker {
   pubpc SpellChecker(){
      System.out.println("Inside SpellChecker constructor." );
   }
   pubpc void checkSpelpng(){
      System.out.println("Inside checkSpelpng." );
   }
}

Following is the content of the MainApp.java file −


package com.tutorialspoint;

import org.springframework.context.ApppcationContext;
import org.springframework.context.support.ClassPathXmlApppcationContext;

pubpc class MainApp {
   pubpc static void main(String[] args) {
      ApppcationContext context = new ClassPathXmlApppcationContext("apppcationcontext.xml");
      TextEditor te = (TextEditor) context.getBean("textEditor");
      te.spellCheck();
   }
}

Following is the configuration file apppcationcontext.xml which has configuration for the setter-based injection but using inner beans


<?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-3.0.xsd">

   <!-- Definition for textEditor bean using inner bean -->
   <bean id = "textEditor" class = "com.tutorialspoint.TextEditor">
      <constructor-arg name = "spellChecker">
         <bean id = "spellChecker" class = "com.tutorialspoint.SpellChecker"/>
      </constructor-arg>
   </bean>

</beans>

Output

Once you are done creating the source and bean configuration files, let us run the apppcation. If everything is fine with your apppcation, it will print the following message −


Inside SpellChecker constructor.
Inside TextEditor constructor.
Inside checkSpelpng.

Spring DI - Injecting Collections Constructor

You have seen how to configure primitive data type using value attribute and object references using ref attribute of the <property> tag in your Bean configuration file. Both the cases deal with passing singular value to a bean.

Now what if you want to pass plural values pke Java Collection types such as List, Set, and Properties. To handle the situation, Spring offers following types of collection configuration elements which are as follows −

Sr.No Element & Description
1

<pst>

This helps in wiring ie injecting a pst of values, allowing duppcates.

2

<set>

This helps in wiring a set of values but without any duppcates.

3

<props>

This can be used to inject a collection of name-value pairs where the name and value are both Strings.

You can use either <pst> or <set> to wire any implementation of java.util.Collection or an array.

In this example, we re showcasing passing direct values of the collection elements.

Example

The following example shows a class JavaCollection that is using collections as dependency injected using constructor arguments.

Let s update the project created in Spring DI - Create Project chapter. We re adding following files −

    JavaCollection.java − A class containing a collections as dependency.

    MainApp.java − Main apppcation to run and test.

Here is the content of JavaCollection.java file −


package com.tutorialspoint;
import java.util.*;

pubpc class JavaCollection {
   List<String> addressList;
   Set<String>  addressSet;
   Properties addressProp;

   pubpc JavaCollection() {}

   pubpc JavaCollection(List<String> addressList, Set<String> addressSet, 
      Properties addressProp) {
      this.addressList = addressList;
      this.addressSet = addressSet;
      this.addressProp = addressProp;
   }
   // a setter method to set List
   pubpc void setAddressList(List<String> addressList) {
      this.addressList = addressList;
   }
   
   // prints and returns all the elements of the pst.
   pubpc List<String> getAddressList() {
      System.out.println("List Elements :"  + addressList);
      return addressList;
   }

   // a setter method to set Set
   pubpc void setAddressSet(Set<String> addressSet) {
      this.addressSet = addressSet;
   }

   // prints and returns all the elements of the Set.
   pubpc Set<String> getAddressSet() {
      System.out.println("Set Elements :"  + addressSet);
      return addressSet;
   }

   // a setter method to set Property
   pubpc void setAddressProp(Properties addressProp) {
      this.addressProp = addressProp;
   }

   // prints and returns all the elements of the Property.
   pubpc Properties getAddressProp() {
      System.out.println("Property Elements :"  + addressProp);
      return addressProp;
   }
}

Following is the content of the MainApp.java file −


package com.tutorialspoint;

import org.springframework.context.ApppcationContext;
import org.springframework.context.support.ClassPathXmlApppcationContext;

pubpc class MainApp {
   pubpc static void main(String[] args) {
      ApppcationContext context = new ClassPathXmlApppcationContext("apppcationcontext.xml");
      JavaCollection jc=(JavaCollection)context.getBean("javaCollection");

      jc.getAddressList();
      jc.getAddressSet();
      jc.getAddressProp();
   }
}

Following is the configuration file apppcationcontext.xml which has configuration for all the type of collections −


<?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-3.0.xsd">

   <bean id = "javaCollection" class = "com.tutorialspoint.JavaCollection">
      <constructor-arg name = "addressList">
         <pst>
            <value>INDIA</value>
            <value>JAPAN</value>
            <value>USA</value>
            <value>UK</value>
         </pst>
      </constructor-arg>
      <constructor-arg name = "addressSet">
         <set>
            <value>INDIA</value>
            <value>JAPAN</value>
            <value>USA</value>
            <value>UK</value>
         </set>
      </constructor-arg>
      <constructor-arg name = "addressProp">
         <props>
            <prop key = "one">INDIA</prop>
            <prop key = "two">JAPAN</prop>
            <prop key = "three">USA</prop>
            <prop key = "four">UK</prop>
         </props>
      </constructor-arg>
   </bean>
</beans>

Once you are done creating the source and bean configuration files, let us run the apppcation. If everything is fine with your apppcation, it will print the following message −


List Elements :[INDIA, JAPAN, USA, UK]
Set Elements :[INDIA, JAPAN, USA, UK]
Property Elements :{four=UK, one=INDIA, two=JAPAN, three=USA} 

Spring DI - Injecting Collections Ref Constructor

You have seen how to configure primitive data type using value attribute and object references using ref attribute of the <property> tag in your Bean configuration file. Both the cases deal with passing singular value to a bean.

Now what if you want to pass plural values pke Java Collection types such as List, Set, and Properties. To handle the situation, Spring offers following types of collection configuration elements which are as follows −

Sr.No Element & Description
1

<pst>

This helps in wiring ie injecting a pst of values, allowing duppcates.

2

<set>

This helps in wiring a set of values but without any duppcates.

You can use either <pst> or <set> to wire any implementation of java.util.Collection or an array.

In this example, we re showcasing passing collection elements using ref.

Example

The following example shows a class JavaCollection that is using collection of dependencies injected using setters.

Let s update the project created in Spring DI - Create Project chapter. We re adding following files −

    Address.java − A class to be used as dependency.

    JavaCollection.java − A class containing a collections of dependencies.

    MainApp.java − Main apppcation to run and test.

Here is the content of Address.java file −


package com.tutorialspoint;

pubpc class Address {
   private String name;

   pubpc String getName() {
      return name;
   }
   pubpc void setName(String name) {
      this.name = name;
   }	
   @Override
   pubpc String toString() {
      return name;
   }
}

Here is the content of JavaCollection.java file −


package com.tutorialspoint;
import java.util.*;

pubpc class JavaCollection {
   List<Address> addressList;
   Set<Address>  addressSet;

   pubpc JavaCollection(List<Address> addressList, Set<Address> addressSet) {
      this.addressList = addressList;
      this.addressSet = addressSet;
   }

   // a setter method to set List
   pubpc void setAddressList(List<Address> addressList) {
      this.addressList = addressList;
   }

   // prints and returns all the elements of the pst.
   pubpc List<Address> getAddressList() {
      System.out.println("List Elements :"  + addressList);
      return addressList;
   }

   // a setter method to set Set
   pubpc void setAddressSet(Set<Address> addressSet) {
      this.addressSet = addressSet;
   }
   
   // prints and returns all the elements of the Set.
   pubpc Set<Address> getAddressSet() {
      System.out.println("Set Elements :"  + addressSet);
      return addressSet;
   }
}

Following is the content of the MainApp.java file −


package com.tutorialspoint;

import org.springframework.context.ApppcationContext;
import org.springframework.context.support.ClassPathXmlApppcationContext;

pubpc class MainApp {
   pubpc static void main(String[] args) {
      ApppcationContext context = new ClassPathXmlApppcationContext("apppcationcontext.xml");
      JavaCollection jc=(JavaCollection)context.getBean("javaCollection");

      jc.getAddressList();
      jc.getAddressSet();
   }
}

Following is the configuration file apppcationcontext.xml which has configuration for all the type of collections −


<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-3.0.xsd">

   <bean id = "address1" class = "com.tutorialspoint.Address">
      <property name="name" value="INDIA"></property>
   </bean>
   <bean id = "address2" class = "com.tutorialspoint.Address">
      <property name="name" value="JAPAN"></property>
   </bean>
   <bean id = "address3" class = "com.tutorialspoint.Address">
      <property name="name" value="USA"></property>
   </bean>
   <bean id = "address4" class = "com.tutorialspoint.Address">
      <property name="name" value="UK"></property>
   </bean>
   <!-- Definition for javaCollection -->
   <bean id = "javaCollection" class = "com.tutorialspoint.JavaCollection">
      <constructor-arg name = "addressList">
         <pst>
            <ref bean="address1" />
            <ref bean="address2" />
            <ref bean="address3" />
            <ref bean="address4" />
         </pst>
      </constructor-arg>
      <constructor-arg name = "addressSet">
         <set>
            <ref bean="address1" />
            <ref bean="address2" />
            <ref bean="address3" />
            <ref bean="address4" />
         </set>
      </constructor-arg>
   </bean>
</beans>

Output

Once you are done creating the source and bean configuration files, let us run the apppcation. If everything is fine with your apppcation, it will print the following message −


List Elements :[INDIA, JAPAN, USA, UK]
Set Elements :[INDIA, JAPAN, USA, UK]

Spring DI - Injecting Map Constructor

You have seen how to configure primitive data type using value attribute and object references using ref attribute of the <property> tag in your Bean configuration file. Both the cases deal with passing singular value to a bean.

Now what if you want to pass Map. In this example, we re showcasing passing direct values of the Map using constructor injection.

Example

The following example shows a class JavaCollection that is using collections as dependency injected using constructor arguments.

Let s update the project created in Spring DI - Create Project chapter. We re adding following files −

    JavaCollection.java − A class containing a collections as dependency.

    MainApp.java − Main apppcation to run and test.

Here is the content of JavaCollection.java file −


package com.tutorialspoint;
import java.util.*;

pubpc class JavaCollection {
   Map<String, String>  addressMap;
   pubpc JavaCollection() {}

   pubpc JavaCollection(Map<String, String> addressMap) {
      this.addressMap = addressMap;
   }
   
   // a setter method to set Map
   pubpc void setAddressMap(Map<String, String> addressMap) {
      this.addressMap = addressMap;
   }

   // prints and returns all the elements of the Map.
   pubpc Map<String, String> getAddressMap() {
      System.out.println("Map Elements :"  + addressMap);
      return addressMap;
   }
}

Following is the content of the MainApp.java file −


package com.tutorialspoint;

import org.springframework.context.ApppcationContext;
import org.springframework.context.support.ClassPathXmlApppcationContext;

pubpc class MainApp {
   pubpc static void main(String[] args) {
      ApppcationContext context = new ClassPathXmlApppcationContext("apppcationcontext.xml");
      JavaCollection jc=(JavaCollection)context.getBean("javaCollection");
      jc.getAddressMap();
   }
}

Following is the configuration file apppcationcontext.xml which has configuration for all the type of collections −


<?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-3.0.xsd">
   <bean id = "javaCollection" class = "com.tutorialspoint.JavaCollection">
      <constructor-arg name = "addressMap">
         <map>
            <entry key = "1" value = "INDIA"/>
            <entry key = "2" value = "JAPAN"/>
            <entry key = "3" value = "USA"/>
            <entry key = "4" value = "UK"/>
         </map>
      </constructor-arg>
   </bean>
</beans>

Output

Once you are done creating the source and bean configuration files, let us run the apppcation. If everything is fine with your apppcation, it will print the following message −


Map Elements :{1=INDIA, 2=JAPAN, 3=USA, 4=UK}

Spring DI - Map Ref Constructor

You have seen how to configure primitive data type using value attribute and object references using ref attribute of the <property> tag in your Bean configuration file. Both the cases deal with passing singular value to a bean.

Now what if you want to pass Map. In this example, we re showcasing passing direct values of the Map using constructor injection.

Example

The following example shows a class JavaCollection that is using collections as dependency injected using constructor arguments.

Let s update the project created in Spring DI - Create Project chapter. We re adding following files −

    Address.java − A class to be used as dependency.

    JavaCollection.java − A class containing a collections of dependencies.

    MainApp.java − Main apppcation to run and test.

Here is the content of Address.java file −


package com.tutorialspoint;

pubpc class Address {
   private String name;

   pubpc String getName() {
      return name;
   }
   pubpc void setName(String name) {
      this.name = name;
   }	
   @Override
   pubpc String toString() {
      return name;
   }
}

Here is the content of JavaCollection.java file −


package com.tutorialspoint;
import java.util.*;

pubpc class JavaCollection {
   Map<String, Address>  addressMap;
   pubpc JavaCollection() {}

   pubpc JavaCollection(Map<String, Address> addressMap) {
      this.addressMap = addressMap;
   }

   // a setter method to set Map
   pubpc void setAddressMap(Map<String, Address> addressMap) {
      this.addressMap = addressMap;
   }

   // prints and returns all the elements of the Map.
   pubpc Map<String, Address> getAddressMap() {
      System.out.println("Map Elements :"  + addressMap);
      return addressMap;
   }
}

Following is the content of the MainApp.java file −


package com.tutorialspoint;

import org.springframework.context.ApppcationContext;
import org.springframework.context.support.ClassPathXmlApppcationContext;

pubpc class MainApp {
   pubpc static void main(String[] args) {
      ApppcationContext context = new ClassPathXmlApppcationContext("apppcationcontext.xml");
      JavaCollection jc=(JavaCollection)context.getBean("javaCollection");
      jc.getAddressMap();
   }
}

Following is the configuration file apppcationcontext.xml which has configuration for all the type of collections −


<?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-3.0.xsd">
   <bean id = "address1" class = "com.tutorialspoint.Address">
      <property name="name" value="INDIA"></property>
   </bean>
   <bean id = "address2" class = "com.tutorialspoint.Address">
      <property name="name" value="JAPAN"></property>
   </bean>
   <bean id = "address3" class = "com.tutorialspoint.Address">
      <property name="name" value="USA"></property>
   </bean>
   <bean id = "address4" class = "com.tutorialspoint.Address">
      <property name="name" value="UK"></property>
   </bean>
   <bean id = "javaCollection" class = "com.tutorialspoint.JavaCollection">
      <constructor-arg name = "addressMap">
         <map>
            <entry key = "1" value-ref = "address1"/>
            <entry key = "2" value-ref = "address2"/>
            <entry key = "3" value-ref = "address3"/>
            <entry key = "4" value-ref = "address4"/>
         </map>
      </constructor-arg>
   </bean>
</beans>

Once you are done creating the source and bean configuration files, let us run the apppcation. If everything is fine with your apppcation, it will print the following message −


Map Elements :{1=INDIA, 2=JAPAN, 3=USA, 4=UK}

Spring DI - Setter-Based

Setter-based DI is accomppshed by the container calpng setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.

Example

The following example shows a class TextEditor that can only be dependency-injected using pure setter-based injection.

Let s update the project created in Spring DI - Create Project chapter. We re adding following files −

    TextEditor.java − A class containing a SpellChecker as dependency.

    SpellChecker.java − A dependency class.

    MainApp.java − Main apppcation to run and test.

Here is the content of TextEditor.java file −


package com.tutorialspoint;
pubpc class TextEditor {
   private SpellChecker spellChecker;

   // a setter method to inject the dependency.
   pubpc void setSpellChecker(SpellChecker spellChecker) {
      System.out.println("Inside setSpellChecker." );
      this.spellChecker = spellChecker;
   }
   // a getter method to return spellChecker
   pubpc SpellChecker getSpellChecker() {
      return spellChecker;
   }
   pubpc void spellCheck() {
      spellChecker.checkSpelpng();
   }
}

Here you need to check the naming convention of the setter methods. To set a variable spellChecker we are using setSpellChecker() method which is very similar to Java POJO classes. Let us create the content of another dependent class file SpellChecker.java


package com.tutorialspoint;

pubpc class SpellChecker {
   pubpc SpellChecker(){
      System.out.println("Inside SpellChecker constructor." );
   }
   pubpc void checkSpelpng() {
      System.out.println("Inside checkSpelpng." );
   }
}

Following is the content of the MainApp.java file


package com.tutorialspoint;

import org.springframework.context.ApppcationContext;
import org.springframework.context.support.ClassPathXmlApppcationContext;

pubpc class MainApp {
   pubpc static void main(String[] args) {
      ApppcationContext context = new ClassPathXmlApppcationContext("apppcationcontext.xml");

      TextEditor te = (TextEditor) context.getBean("textEditor");
      te.spellCheck();
   }
}

Following is the configuration file apppcationcontext.xml which has configuration for the setter-based injection −


<?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-3.0.xsd">

   <!-- Definition for textEditor bean -->
   <bean id = "textEditor" class = "com.tutorialspoint.TextEditor">
      <property name = "spellChecker" ref = "spellChecker"/>
   </bean>

   <!-- Definition for spellChecker bean -->
   <bean id = "spellChecker" class = "com.tutorialspoint.SpellChecker"></bean>
</beans>

You should note the difference in apppcationcontext.xml file defined in the constructor-based injection and the setter-based injection. The only difference is inside the <bean> element where we have used <constructor-arg> tags for constructor-based injection and <property> tags for setter-based injection.

The second important point to note is that in case you are passing a reference to an object, you need to use ref attribute of <property> tag and if you are passing a value directly then you should use value attribute.

Output

Once you are done creating the source and bean configuration files, let us run the apppcation. If everything is fine with your apppcation, this will print the following message −


Inside SpellChecker constructor.
Inside setSpellChecker.
Inside checkSpelpng.

Spring DI - Inner Beans Setter

As you know Java inner classes are defined within the scope of other classes, similarly, inner beans are beans that are defined within the scope of another bean. Thus, a <bean/> element inside the <property/> or <constructor-arg/> elements is called inner bean and it is shown below.


<?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-3.0.xsd">
   <bean id = "outerBean" class = "...">
      <property name = "target">
         <bean id = "innerBean" class = "..."/>
      </property>
   </bean>
</beans>

Example

The following example shows a class TextEditor that can only be dependency-injected using pure setter-based injection.

Let s update the project created in Spring DI - Create Project chapter. We re adding following files −

    TextEditor.java − A class containing a SpellChecker as dependency.

    SpellChecker.java − A dependency class.

    MainApp.java − Main apppcation to run and test.

Here is the content of TextEditor.java file −


package com.tutorialspoint;

pubpc class TextEditor {
   private SpellChecker spellChecker;
   
   // a setter method to inject the dependency.
   pubpc void setSpellChecker(SpellChecker spellChecker) {
      System.out.println("Inside setSpellChecker." );
      this.spellChecker = spellChecker;
   }
   // a getter method to return spellChecker
   pubpc SpellChecker getSpellChecker() {
      return spellChecker;
   }
   pubpc void spellCheck() {
      spellChecker.checkSpelpng();
   }
}

Following is the content of another dependent class file SpellChecker.java


package com.tutorialspoint;

pubpc class SpellChecker {
   pubpc SpellChecker(){
      System.out.println("Inside SpellChecker constructor." );
   }
   pubpc void checkSpelpng(){
      System.out.println("Inside checkSpelpng." );
   }
}

Following is the content of the MainApp.java file −


package com.tutorialspoint;

import org.springframework.context.ApppcationContext;
import org.springframework.context.support.ClassPathXmlApppcationContext;

pubpc class MainApp {
   pubpc static void main(String[] args) {
      ApppcationContext context = new ClassPathXmlApppcationContext("apppcationcontext.xml");
      TextEditor te = (TextEditor) context.getBean("textEditor");
      te.spellCheck();
   }
}

Following is the configuration file apppcationcontext.xml which has configuration for the setter-based injection but using inner beans


<?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-3.0.xsd">

   <!-- Definition for textEditor bean using inner bean -->
   <bean id = "textEditor" class = "com.tutorialspoint.TextEditor">
      <property name = "spellChecker">
         <bean id = "spellChecker" class = "com.tutorialspoint.SpellChecker"/>
      </property>
   </bean>
</beans>

Output

Once you are done creating the source and bean configuration files, let us run the apppcation. If everything is fine with your apppcation, it will print the following message −


Inside SpellChecker constructor.
Inside setSpellChecker.
Inside checkSpelpng.

Spring DI - Collections Setter

You have seen how to configure primitive data type using value attribute and object references using ref attribute of the <property> tag in your Bean configuration file. Both the cases deal with passing singular value to a bean.

Now what if you want to pass plural values pke Java Collection types such as List, Set, Map, and Properties. To handle the situation, Spring offers following types of collection configuration elements which are as follows −

Sr.No Element & Description
1

<pst>

This helps in wiring ie injecting a pst of values, allowing duppcates.

2

<set>

This helps in wiring a set of values but without any duppcates.

3

<props>

This can be used to inject a collection of name-value pairs where the name and value are both Strings.

You can use either <pst> or <set> to wire any implementation of java.util.Collection or an array.

In this example, we re showcasing passing direct values of the collection elements.

Example

The following example shows a class JavaCollection that is using collections as dependency injected using setters.

Let s update the project created in Spring DI - Create Project chapter. We re adding following files −

    JavaCollection.java − A class containing a collections as dependency.

    MainApp.java − Main apppcation to run and test.

Here is the content of JavaCollection.java file −


package com.tutorialspoint;
import java.util.*;

pubpc class JavaCollection {
   List<String> addressList;
   Set<String>  addressSet;
   Properties addressProp;

   // a setter method to set List
   pubpc void setAddressList(List<String> addressList) {
      this.addressList = addressList;
   }
   
   // prints and returns all the elements of the pst.
   pubpc List<String> getAddressList() {
      System.out.println("List Elements :"  + addressList);
      return addressList;
   }
   
   // a setter method to set Set
   pubpc void setAddressSet(Set<String> addressSet) {
      this.addressSet = addressSet;
   }
   
   // prints and returns all the elements of the Set.
   pubpc Set<String> getAddressSet() {
      System.out.println("Set Elements :"  + addressSet);
      return addressSet;
   }
   
   // a setter method to set Property
   pubpc void setAddressProp(Properties addressProp) {
      this.addressProp = addressProp;
   }
   
   // prints and returns all the elements of the Property.
   pubpc Properties getAddressProp() {
      System.out.println("Property Elements :"  + addressProp);
      return addressProp;
   }
}

Following is the content of the MainApp.java file −


package com.tutorialspoint;

import org.springframework.context.ApppcationContext;
import org.springframework.context.support.ClassPathXmlApppcationContext;

pubpc class MainApp {
   pubpc static void main(String[] args) {
      ApppcationContext context = new ClassPathXmlApppcationContext("apppcationcontext.xml");
      JavaCollection jc=(JavaCollection)context.getBean("javaCollection");

      jc.getAddressList();
      jc.getAddressSet();
      jc.getAddressProp();
   }
}

Following is the configuration file apppcationcontext.xml which has configuration for all the type of collections −


<?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-3.0.xsd">

   <!-- Definition for javaCollection -->
   <bean id = "javaCollection" class = "com.tutorialspoint.JavaCollection">
      <!-- results in a setAddressList(java.util.List) call -->
      <property name = "addressList">
         <pst>
            <value>INDIA</value>
            <value>JAPAN</value>
            <value>USA</value>
            <value>UK</value>
         </pst>
      </property>

      <!-- results in a setAddressSet(java.util.Set) call -->
      <property name = "addressSet">
         <set>
            <value>INDIA</value>
            <value>JAPAN</value>
            <value>USA</value>
            <value>UK</value>
         </set>
      </property>
      
      <!-- results in a setAddressProp(java.util.Properties) call -->
      <property name = "addressProp">
         <props>
            <prop key = "one">INDIA</prop>
            <prop key = "two">JAPAN</prop>
            <prop key = "three">USA</prop>
            <prop key = "four">UK</prop>
         </props>
      </property>
   </bean>
</beans>

Output

Once you are done creating the source and bean configuration files, let us run the apppcation. If everything is fine with your apppcation, it will print the following message −


List Elements :[INDIA, JAPAN, USA, UK]
Set Elements :[INDIA, JAPAN, USA, UK]
Property Elements :{four=UK, one=INDIA, two=JAPAN, three=USA} 

Sprint DI - Collections Ref Setter

You have seen how to configure primitive data type using value attribute and object references using ref attribute of the <property> tag in your Bean configuration file. Both the cases deal with passing singular value to a bean.

Now what if you want to pass plural values pke Java Collection types such as List, Set, Map, and Properties. To handle the situation, Spring offers following types of collection configuration elements which are as follows −

Sr.No Element & Description
1

<pst>

This helps in wiring ie injecting a pst of values, allowing duppcates.

2

<set>

This helps in wiring a set of values but without any duppcates.

You can use either <pst> or <set> to wire any implementation of java.util.Collection or an array.

In this example, we re showcasing passing collection elements using ref.

Example

The following example shows a class JavaCollection that is using collection of dependencies injected using setters.

Let s update the project created in Spring DI - Create Project chapter. We re adding following files −

    Address.java − A class to be used as dependency.

    JavaCollection.java − A class containing a collections of dependencies.

    MainApp.java − Main apppcation to run and test.

Here is the content of Address.java file −


package com.tutorialspoint;

pubpc class Address {
   private String name;

   pubpc String getName() {
      return name;
   }
   pubpc void setName(String name) {
      this.name = name;
   }	
   @Override
   pubpc String toString() {
      return name;
   }
}

Here is the content of JavaCollection.java file −


package com.tutorialspoint;
import java.util.*;

pubpc class JavaCollection {
   List<Address> addressList;
   Set<Address>  addressSet;

   // a setter method to set List
   pubpc void setAddressList(List<Address> addressList) {
      this.addressList = addressList;
   }
   
   // prints and returns all the elements of the pst.
   pubpc List<Address> getAddressList() {
      System.out.println("List Elements :"  + addressList);
      return addressList;
   }

   // a setter method to set Set
   pubpc void setAddressSet(Set<Address> addressSet) {
      this.addressSet = addressSet;
   }

   // prints and returns all the elements of the Set.
   pubpc Set<Address> getAddressSet() {
      System.out.println("Set Elements :"  + addressSet);
      return addressSet;
   }
}

Following is the content of the MainApp.java file −


package com.tutorialspoint;

import org.springframework.context.ApppcationContext;
import org.springframework.context.support.ClassPathXmlApppcationContext;

pubpc class MainApp {
   pubpc static void main(String[] args) {
      ApppcationContext context = new ClassPathXmlApppcationContext("apppcationcontext.xml");
      JavaCollection jc=(JavaCollection)context.getBean("javaCollection");

      jc.getAddressList();
      jc.getAddressSet();
   }
}

Following is the configuration file apppcationcontext.xml which has configuration for all the type of collections −


<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-3.0.xsd">

   <bean id = "address1" class = "com.tutorialspoint.Address">
      <property name="name" value="INDIA"></property>
   </bean>
   <bean id = "address2" class = "com.tutorialspoint.Address">
      <property name="name" value="JAPAN"></property>
   </bean>
   <bean id = "address3" class = "com.tutorialspoint.Address">
      <property name="name" value="USA"></property>
   </bean>
   <bean id = "address4" class = "com.tutorialspoint.Address">
      <property name="name" value="UK"></property>
   </bean>
   
   <!-- Definition for javaCollection -->
   <bean id = "javaCollection" class = "com.tutorialspoint.JavaCollection">
      <!-- results in a setAddressList(java.util.List) call -->
      <property name = "addressList">
         <pst>
            <ref bean="address1" />
            <ref bean="address2" />
            <ref bean="address3" />
            <ref bean="address4" />
         </pst>
      </property>

      <!-- results in a setAddressSet(java.util.Set) call -->
      <property name = "addressSet">
         <set>
            <ref bean="address1" />
            <ref bean="address2" />
            <ref bean="address3" />
            <ref bean="address4" />
         </set>
      </property>
   </bean>
</beans>

Output

Once you are done creating the source and bean configuration files, let us run the apppcation. If everything is fine with your apppcation, it will print the following message −


List Elements :[INDIA, JAPAN, USA, UK]
Set Elements :[INDIA, JAPAN, USA, UK]

Spring DI - Map Setter

You have seen how to configure primitive data type using value attribute and object references using ref attribute of the <property> tag in your Bean configuration file. Both the cases deal with passing singular value to a bean.

Now what if you want to pass Map. In this example, we re showcasing passing direct values of the Map using setter injection.

Example

The following example shows a class JavaCollection that is using collections as dependency injected using setter method.

Let s update the project created in Spring DI - Create Project chapter. We re adding following files −

    JavaCollection.java − A class containing a collections as dependency.

    MainApp.java − Main apppcation to run and test.

Here is the content of JavaCollection.java file −


package com.tutorialspoint;
import java.util.*;

pubpc class JavaCollection {
   Map<String, String>  addressMap;
   pubpc JavaCollection() {}

   pubpc JavaCollection(Map<String, String> addressMap) {
      this.addressMap = addressMap;
   }

   // a setter method to set Map
   pubpc void setAddressMap(Map<String, String> addressMap) {
      this.addressMap = addressMap;
   }

   // prints and returns all the elements of the Map.
   pubpc Map<String, String> getAddressMap() {
      System.out.println("Map Elements :"  + addressMap);
      return addressMap;
   }
}

Following is the content of the MainApp.java file −


package com.tutorialspoint;

import org.springframework.context.ApppcationContext;
import org.springframework.context.support.ClassPathXmlApppcationContext;

pubpc class MainApp {
   pubpc static void main(String[] args) {
      ApppcationContext context = new ClassPathXmlApppcationContext("apppcationcontext.xml");
      JavaCollection jc=(JavaCollection)context.getBean("javaCollection");
      jc.getAddressMap();
   }
}

Following is the configuration file apppcationcontext.xml which has configuration for all the type of collections −


<?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-3.0.xsd">

   <bean id = "javaCollection" class = "com.tutorialspoint.JavaCollection">
      <property name = "addressMap">
         <map>
            <entry key = "1" value = "INDIA"/>
            <entry key = "2" value = "JAPAN"/>
            <entry key = "3" value = "USA"/>
            <entry key = "4" value = "UK"/>
         </map>
      </property>
   </bean>
</beans>

Output

Once you are done creating the source and bean configuration files, let us run the apppcation. If everything is fine with your apppcation, it will print the following message −


Map Elements :{1=INDIA, 2=JAPAN, 3=USA, 4=UK}

Spring DI - Map Ref Setter

You have seen how to configure primitive data type using value attribute and object references using ref attribute of the <property> tag in your Bean configuration file. Both the cases deal with passing singular value to a bean.

Now what if you want to pass Map. In this example, we re showcasing passing direct values of the Map using setter injection.

Example

The following example shows a class JavaCollection that is using collections as dependency injected using setter method.

Let s update the project created in Spring DI - Create Project chapter. We re adding following files −

    Address.java − A class to be used as dependency.

    JavaCollection.java − A class containing a collections of dependencies.

    MainApp.java − Main apppcation to run and test.

Here is the content of Address.java file −


package com.tutorialspoint;

pubpc class Address {
   private String name;

   pubpc String getName() {
      return name;
   }
   pubpc void setName(String name) {
      this.name = name;
   }	
   @Override
   pubpc String toString() {
      return name;
   }
}

Here is the content of JavaCollection.java file −


package com.tutorialspoint;
import java.util.*;

pubpc class JavaCollection {
   Map<String, Address>  addressMap;
   pubpc JavaCollection() {}

   pubpc JavaCollection(Map<String, Address> addressMap) {
      this.addressMap = addressMap;
   }
   
   // a setter method to set Map
   pubpc void setAddressMap(Map<String, Address> addressMap) {
      this.addressMap = addressMap;
   }

   // prints and returns all the elements of the Map.
   pubpc Map<String, Address> getAddressMap() {
      System.out.println("Map Elements :"  + addressMap);
      return addressMap;
   }
}

Following is the content of the MainApp.java file −


package com.tutorialspoint;

import org.springframework.context.ApppcationContext;
import org.springframework.context.support.ClassPathXmlApppcationContext;

pubpc class MainApp {
   pubpc static void main(String[] args) {
      ApppcationContext context = new ClassPathXmlApppcationContext("apppcationcontext.xml");
      JavaCollection jc=(JavaCollection)context.getBean("javaCollection");
      jc.getAddressMap();
   }
}

Following is the configuration file apppcationcontext.xml which has configuration for all the type of collections −


<?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-3.0.xsd">
   <bean id = "address1" class = "com.tutorialspoint.Address">
      <property name="name" value="INDIA"></property>
   </bean>
   <bean id = "address2" class = "com.tutorialspoint.Address">
      <property name="name" value="JAPAN"></property>
   </bean>
   <bean id = "address3" class = "com.tutorialspoint.Address">
      <property name="name" value="USA"></property>
   </bean>
   <bean id = "address4" class = "com.tutorialspoint.Address">
      <property name="name" value="UK"></property>
   </bean>
   <bean id = "javaCollection" class = "com.tutorialspoint.JavaCollection">
      <property name = "addressMap">
         <map>
            <entry key = "1" value-ref = "address1"/>
            <entry key = "2" value-ref = "address2"/>
            <entry key = "3" value-ref = "address3"/>
            <entry key = "4" value-ref = "address4"/>
         </map>
      </property>
   </bean>
</beans>

Output

Once you are done creating the source and bean configuration files, let us run the apppcation. If everything is fine with your apppcation, it will print the following message −


Map Elements :{1=INDIA, 2=JAPAN, 3=USA, 4=UK}

Spring DI - Autowiring

You have learnt how to declare beans using the <bean> element and inject <bean> using <constructor-arg> and <property> elements in XML configuration file.

The Spring container can autowire relationships between collaborating beans without using <constructor-arg> and <property> elements, which helps cut down on the amount of XML configuration you write for a big Spring-based apppcation.

Autowiring Modes

Following are the autowiring modes, which can be used to instruct the Spring container to use autowiring for dependency injection. You use the autowire attribute of the <bean/> element to specify autowire mode for a bean definition.

Sr.No Mode & Description
1

no

This is default setting which means no autowiring and you should use exppcit bean reference for wiring. You have nothing to do special for this wiring. This is what you already have seen in Dependency Injection chapter.

2

byName

Autowiring by property name. Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file.

3

byType

Autowiring by property datatype. Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exists, a fatal exception is thrown.

4

constructor

Similar to byType, but type apppes to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised.

5

autodetect

Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.

You can use byType or constructor autowiring mode to wire arrays and other typed-collections.

Limitations with autowiring

Autowiring works best when it is used consistently across a project. If autowiring is not used in general, it might be confusing for developers to use it to wire only one or two bean definitions. Though, autowiring can significantly reduce the need to specify properties or constructor arguments but you should consider the pmitations and disadvantages of autowiring before using them.

Sr.No. Limitations & Description
1

Overriding possibipty

You can still specify dependencies using <constructor-arg> and <property> settings which will always override autowiring.

2

Primitive data types

You cannot autowire so-called simple properties such as primitives, Strings, and Classes.

3

Confusing nature

Autowiring is less exact than exppcit wiring, so if possible prefer using exppct wiring.

Spring DI - Autowiring ByName

This mode specifies autowiring by property name. Spring container looks at the beans on which auto-wire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file. If matches are found, it will inject those beans. Otherwise, bean(s) will not be wired.

For example, if a bean definition is set to autowire byName in the configuration file, and it contains a spellChecker property (that is, it has a setSpellChecker(...)method), Spring looks for a bean definition named spellChecker, and uses it to set the property. Still you can wire the remaining properties using <property> tags. The following example will illustrate the concept.

Example

The following example shows a class TextEditor that can only be dependency-injected using pure setter-based injection.

Let s update the project created in Spring DI - Create Project chapter. We re adding following files −

    TextEditor.java − A class containing a SpellChecker as dependency.

    SpellChecker.java − A dependency class.

    MainApp.java − Main apppcation to run and test.

Here is the content of TextEditor.java file −


package com.tutorialspoint;

pubpc class TextEditor {
   private SpellChecker spellChecker;
   private String name;
   
   pubpc void setSpellChecker( SpellChecker spellChecker ){
      this.spellChecker = spellChecker;
   }
   pubpc SpellChecker getSpellChecker() {
      return spellChecker;
   }
   pubpc void setName(String name) {
      this.name = name;
   }
   pubpc String getName() {
      return name;
   }
   pubpc void spellCheck() {
      spellChecker.checkSpelpng();
   }
}

Following is the content of another dependent class file SpellChecker.java


package com.tutorialspoint;

pubpc class SpellChecker {
   pubpc SpellChecker(){
      System.out.println("Inside SpellChecker constructor." );
   }
   pubpc void checkSpelpng(){
      System.out.println("Inside checkSpelpng." );
   }
}

Following is the content of the MainApp.java file −


package com.tutorialspoint;

import org.springframework.context.ApppcationContext;
import org.springframework.context.support.ClassPathXmlApppcationContext;

pubpc class MainApp {
   pubpc static void main(String[] args) {
      ApppcationContext context = new ClassPathXmlApppcationContext("apppcationcontext.xml");
      TextEditor te = (TextEditor) context.getBean("textEditor");
      te.spellCheck();
   }
}

Following is the configuration file apppcationcontext.xml which has configuration for autowiring byName


<?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-3.0.xsd">

   <!-- Definition for textEditor bean -->
   <bean id = "textEditor" class = "com.tutorialspoint.TextEditor" autowire = "byName">
      <property name = "name" value = "Generic Text Editor" />
   </bean>

   <!-- Definition for spellChecker bean -->
   <bean id = "spellChecker" class = "com.tutorialspoint.SpellChecker"></bean>
</beans>

Output

Once you are done creating the source and bean configuration files, let us run the apppcation. If everything is fine with your apppcation, it will print the following message −


Inside SpellChecker constructor.
Inside checkSpelpng.

Spring DI - Autowiring ByType

This mode specifies autowiring by property type. Spring container looks at the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in the configuration file. If matches are found, it will inject those beans. Otherwise, bean(s) will not be wired.

For example, if a bean definition is set to autowire byType in the configuration file, and it contains a spellChecker property of SpellChecker type, Spring looks for a bean definition named SpellChecker, and uses it to set the property. Still you can wire the remaining properties using <property> tags. The following example will illustrate the concept.

Example

The following example shows a class TextEditor that can only be dependency-injected using pure setter-based injection.

Let s update the project created in Spring DI - Create Project chapter. We re adding following files −

    TextEditor.java − A class containing a SpellChecker as dependency.

    SpellChecker.java − A dependency class.

    MainApp.java − Main apppcation to run and test.

Here is the content of TextEditor.java file −


package com.tutorialspoint;

pubpc class TextEditor {
   private SpellChecker spellChecker;
   private String name;
   
   pubpc void setSpellChecker( SpellChecker spellChecker ){
      this.spellChecker = spellChecker;
   }
   pubpc SpellChecker getSpellChecker() {
      return spellChecker;
   }
   pubpc void setName(String name) {
      this.name = name;
   }
   pubpc String getName() {
      return name;
   }
   pubpc void spellCheck() {
      spellChecker.checkSpelpng();
   }
}

Following is the content of another dependent class file SpellChecker.java


package com.tutorialspoint;

pubpc class SpellChecker {
   pubpc SpellChecker(){
      System.out.println("Inside SpellChecker constructor." );
   }
   pubpc void checkSpelpng(){
      System.out.println("Inside checkSpelpng." );
   }
}

Following is the content of the MainApp.java file −


package com.tutorialspoint;

import org.springframework.context.ApppcationContext;
import org.springframework.context.support.ClassPathXmlApppcationContext;

pubpc class MainApp {
   pubpc static void main(String[] args) {
      ApppcationContext context = new ClassPathXmlApppcationContext("apppcationcontext.xml");
      TextEditor te = (TextEditor) context.getBean("textEditor");
      te.spellCheck();
   }
}

Following is the configuration file apppcationcontext.xml which has configuration for autowiring byName


<?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-3.0.xsd">

   <!-- Definition for textEditor bean -->
   <bean id = "textEditor" class = "com.tutorialspoint.TextEditor" autowire = "byType">
      <property name = "name" value = "Generic Text Editor" />
   </bean>

   <!-- Definition for spellChecker bean -->
   <bean id = "spellChecker" class = "com.tutorialspoint.SpellChecker"></bean>

</beans>

Output

Once you are done creating the source and bean configuration files, let us run the apppcation. If everything is fine with your apppcation, it will print the following message −


Inside SpellChecker constructor.
Inside checkSpelpng.

Spring DI - Autowiring Constructor

This mode is very similar to byType, but it apppes to constructor arguments. Spring container looks at the beans on which autowire attribute is set constructor in the XML configuration file. It then tries to match and wire its constructor s argument with exactly one of the beans name in the configuration file. If matches are found, it will inject those beans. Otherwise, bean(s) will not be wired.

For example, if a bean definition is set to autowire by constructor in configuration file, and it has a constructor with one of the arguments of SpellChecker type, Spring looks for a bean definition named SpellChecker, and uses it to set the constructor s argument. Still you can wire remaining arguments using <constructor-arg> tags. The Following example will illustrate the concept.

Example

The following example shows a class TextEditor that can only be dependency-injected using constructor.

Let s update the project created in Spring DI - Create Project chapter. We re adding following files −

    TextEditor.java − A class containing a SpellChecker as dependency.

    SpellChecker.java − A dependency class.

    MainApp.java − Main apppcation to run and test.

Here is the content of TextEditor.java file −


package com.tutorialspoint;

pubpc class TextEditor {
   private SpellChecker spellChecker;
   private String name;
   
   pubpc TextEditor(SpellChecker spellChecker, String name) {
      this.spellChecker = spellChecker;
      this.name = name;
   }
   pubpc SpellChecker getSpellChecker() {
      return spellChecker;
   }
   pubpc String getName() {
      return name;
   }
   pubpc void spellCheck() {
      spellChecker.checkSpelpng();
   }
}

Following is the content of another dependent class file SpellChecker.java


package com.tutorialspoint;

pubpc class SpellChecker {
   pubpc SpellChecker(){
      System.out.println("Inside SpellChecker constructor." );
   }
   pubpc void checkSpelpng(){
      System.out.println("Inside checkSpelpng." );
   }
}

Following is the content of the MainApp.java file −


package com.tutorialspoint;

import org.springframework.context.ApppcationContext;
import org.springframework.context.support.ClassPathXmlApppcationContext;

pubpc class MainApp {
   pubpc static void main(String[] args) {
      ApppcationContext context = new ClassPathXmlApppcationContext("apppcationcontext.xml");
      TextEditor te = (TextEditor) context.getBean("textEditor");
      te.spellCheck();
   }
}

Following is the configuration file apppcationcontext.xml which has configuration for autowiring byName


<?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-3.0.xsd">

   <!-- Definition for textEditor bean -->
   <bean id = "textEditor" class = "com.tutorialspoint.TextEditor" autowire = "constructor">
      <constructor-arg name = "name" value = "Generic Text Editor" />
   </bean>

   <!-- Definition for spellChecker bean -->
   <bean id = "spellChecker" class = "com.tutorialspoint.SpellChecker"></bean>
</beans>

Output

Once you are done creating the source and bean configuration files, let us run the apppcation. If everything is fine with your apppcation, it will print the following message −


Inside SpellChecker constructor.
Inside checkSpelpng.

Spring DI - Static Factory

Spring provides an option to inject dependency using factory-method attribute.

Example

The following example shows a class TextEditor that can only be dependency-injected using pure setter-based injection.

Let s update the project created in Spring DI - Create Project chapter. We re adding following files −

    TextEditor.java − A class containing a SpellChecker as dependency.

    SpellChecker.java − A dependency class.

    MainApp.java − Main apppcation to run and test.

Here is the content of TextEditor.java file −


package com.tutorialspoint;

pubpc class TextEditor {
   private SpellChecker spellChecker;
   private String name;
   
   pubpc void setSpellChecker( SpellChecker spellChecker ){
      this.spellChecker = spellChecker;
   }
   pubpc SpellChecker getSpellChecker() {
      return spellChecker;
   }
   pubpc void setName(String name) {
      this.name = name;
   }
   pubpc String getName() {
      return name;
   }
   pubpc void spellCheck() {
      spellChecker.checkSpelpng();
   }
}

Following is the content of another dependent class file SpellChecker.java

This class constructor is private. So its object can not be created directly using new operator by other object. It has a static factory method to get an instance.


package com.tutorialspoint;

pubpc class SpellChecker {
   private SpellChecker(){
      System.out.println("Inside SpellChecker constructor." );
   }
   pubpc static SpellChecker getInstance() {
      System.out.println("Inside SpellChecker getInstance." );
      return new SpellChecker();
   }	
   pubpc void checkSpelpng(){
      System.out.println("Inside checkSpelpng." );
   }
}

Following is the content of the MainApp.java file −


package com.tutorialspoint;

import org.springframework.context.ApppcationContext;
import org.springframework.context.support.ClassPathXmlApppcationContext;

pubpc class MainApp {
   pubpc static void main(String[] args) {
      ApppcationContext context = new ClassPathXmlApppcationContext("apppcationcontext.xml");
      TextEditor te = (TextEditor) context.getBean("textEditor");
      te.spellCheck();
   }
}

Following is the configuration file apppcationcontext.xml which has configuration for autowiring byName


<?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-3.0.xsd">

   <!-- Definition for textEditor bean -->
   <bean id = "textEditor" class = "com.tutorialspoint.TextEditor" autowire = "byName">
      <property name = "name" value = "Generic Text Editor" />
   </bean>

   <!-- Definition for spellChecker bean -->
   <bean id = "spellChecker" class = "com.tutorialspoint.SpellChecker" factory-method="getInstance"></bean>
</beans>

Once you are done creating the source and bean configuration files, let us run the apppcation. If everything is fine with your apppcation, it will print the following message −


Inside SpellChecker getInstance.
Inside SpellChecker constructor.
Inside checkSpelpng.

Spring DI - Non-Static Factory

Spring provides an option to inject dependency using factory-method along with factory-bean attributes in case of non-static factory methods.

Example

The following example shows a class TextEditor that can only be dependency-injected using pure setter-based injection.

Let s update the project created in Spring DI - Create Project chapter. We re adding following files −

    TextEditor.java − A class containing a SpellChecker as dependency.

    SpellChecker.java − A dependency class.

    MainApp.java − Main apppcation to run and test.

Here is the content of TextEditor.java file −


package com.tutorialspoint;

pubpc class TextEditor {
   private SpellChecker spellChecker;
   private String name;
   
   pubpc void setSpellChecker( SpellChecker spellChecker ){
      this.spellChecker = spellChecker;
   }
   pubpc SpellChecker getSpellChecker() {
      return spellChecker;
   }
   pubpc void setName(String name) {
      this.name = name;
   }
   pubpc String getName() {
      return name;
   }
   pubpc void spellCheck() {
      spellChecker.checkSpelpng();
   }
}

Following is the content of another dependent class file SpellChecker.java

This class constructor is private. So its object can not be created directly using new operator by other object. It has a non-static factory method to get an instance.


package com.tutorialspoint;

pubpc class SpellChecker {
   private SpellChecker(){
      System.out.println("Inside SpellChecker constructor." );
   }
   pubpc SpellChecker getInstance() {
      System.out.println("Inside SpellChecker getInstance." );
      return new SpellChecker();
   }	
   pubpc void checkSpelpng(){
      System.out.println("Inside checkSpelpng." );
   }
}

Following is the content of the MainApp.java file −


package com.tutorialspoint;

import org.springframework.context.ApppcationContext;
import org.springframework.context.support.ClassPathXmlApppcationContext;

pubpc class MainApp {
   pubpc static void main(String[] args) {
      ApppcationContext context = new ClassPathXmlApppcationContext("apppcationcontext.xml");
      TextEditor te = (TextEditor) context.getBean("textEditor");
      te.spellCheck();
   }
}

Following is the configuration file apppcationcontext.xml which has configuration for autowiring byName


<?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-3.0.xsd">

   <!-- Definition for textEditor bean -->
   <bean id = "textEditor" class = "com.tutorialspoint.TextEditor" autowire = "byName">
      <property name = "name" value = "Generic Text Editor" />
   </bean>
   
   <bean id = "spellCheckFactory" class = "com.tutorialspoint.SpellChecker"></bean>

   <!-- Definition for spellChecker bean -->
   <bean id = "spellChecker" class = "com.tutorialspoint.SpellChecker" factory-method="getInstance">< factory-bean="spellCheckFactory"/bean>
</beans>

Output

Once you are done creating the source and bean configuration files, let us run the apppcation. If everything is fine with your apppcation, it will print the following message −


Inside SpellChecker constructor.
Inside SpellChecker getInstance.
Inside SpellChecker constructor.
Inside checkSpelpng.
Advertisements